여기에 배열과 변수를 선언했습니다. productList 배열, 이름, 가격 및 번호
import java.io.*;
import java.util.*;
public class ReadingAndWritting {
public String name;
public double price;
public int number;
public ReadingAndWritting[] productList = new ReadingAndWritting[3];
public ReadingAndWritting() {
}
public ReadingAndWritting(String name, double price, int number) {
this.name = name;
this.price = price;
this.number = number;
}
public void printContents() {
int i = 0;
try {
FileReader fl = new FileReader("Product List.txt");
Scanner scn = new Scanner(fl);
while (scn.hasNext()) {
String productName = scn.next();
double productPrice = scn.nextDouble();
int productAmount = scn.nextInt();
System.out.println(productName + " is " + productPrice + " pula. There are " + productAmount + " items left in stalk.");
productList[i] = new ReadingAndWritting(productName, productPrice, productAmount);
i = i + 1;
}
scn.close();
} catch (IOException exc) {
exc.printStackTrace();
} catch (Exception exc) {
exc.printStackTrace();
}
}
public void writeContents() {
try {
//FileOutputStream formater = new FileOutputStream("Product List.txt",true);
Formatter writer = new Formatter(new FileOutputStream("Product List.txt", true));
for (int i = 0; i < productList.length; ++i) {
writer.format(name, (price + 100.0), (number - 1), "\n");
}
writer.close();
} catch (IOException exc) {
exc.printStackTrace();
}
}
public static void main(String[] args) {
ReadingAndWritting obj = new ReadingAndWritting();
System.out.println("_____THIS IS THE BEGINNING OF THE PRODUCT LIST_____");
obj.printContents();
System.out.println("_____THIS IS THE END OF THE PRODUCT LIST_____");
System.out.println("_____THIS IS THE BEGINNING OF THE PRODUCT LIST_____");
obj.writeContents();
obj.printContents();
System.out.println("_____THIS IS THE END OF THE PRODUCT LIST_____");
}
}
코드를 실행할 때마다 기존 파일의 형식을 지정하고 NullPointerException을보고합니다. 나는 이것을 고치는 방법에 대해 완전히 잃어 버렸고 강사는 그것을 다루지 않았습니다. 부디
productList [] 배열에는 각 식별자에 포함 된 이름, 가격 및 숫자 값이 있습니다. 기존 파일의 내용을 지우고 새 값으로 작성하여 배열의 내용을 업데이트하고 싶습니다.
사용중인 생성자는 Javadoc에 명확하게 명시된대로 입력 파일을 자릅니다.
fileName 이 포맷터의 대상으로 사용할 파일의 이름입니다. 파일이 존재 하면 0 크기 로 잘립니다 . 그렇지 않으면 새 파일이 생성됩니다. 출력은 파일에 기록되고 버퍼링됩니다.
Formatter(OutputStream os)
잘림을 방지하기 위해 다른 생성자를 사용할 수 있습니다 .
Formatter writer = new Formatter(new FileOutputStream("Product List.txt",true));
에 대한 NullPointerException
귀하의 의견을보고 :
public String name;
name
초기화되지 않았으므로 null
기본적으로 NullPointerException
.
PS 내가 모르는 productList
이름과 당신이 그것을 반복된다는 사실에 기초, 아마도 당신이 얻을해야함으로써, price
그리고 name
그 목록의 요소에서.
편집하다 :
나머지 코드를 기반으로 productList
배열 에서 값을 가져와야합니다.
for (int i = 0; i < productList.length; ++i) {
writer.format(productList[i].name, (productList[i].price + 100.0), (productList[i].number - 1), "\n");
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다