0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

つまづいたところ

Javaの勉強中、下記コードでnullpointerexceptionが発生。 配列インスタンスを生成し、各インスタンスに値をセットしようとしたところ、fruits[i].setFields~の部分でエラー。
Practice2.java
public class Practice2 {
	public static void main(String[] args) {
		try {
			File file = new File("C:/java/testdata.txt");

			//ファイルの行数を取得
			Path path = Paths.get("C:/java/testdata.txt");
			int lineCount = (int)Files.lines(path).count();
			
			if (!file.exists()) {
				System.out.println(file + "がありません");
				return;
			} else {
				FileReader fr = new FileReader(file);
				BufferedReader br = new BufferedReader(fr);
				String s;
				int i = 0;
				//配列インスタンスの生成
				FruitData[] fruits = new FruitData[lineCount];
				while((s = br.readLine()) != null) {
					String[] fruit = s.split(",");
					fruits[i].setFields( Integer.parseInt(fruit[0]),fruit[1],Integer.parseInt(fruit[2]));
					fruits[i].printInfo();
					i++;
				}
				br.close();
			}
		} catch (IOException e) {
			System.out.println(e);
		}
	}
}

結論、配列インスタンスの作成はしたものの、個別のインスタンス生成を行っていないからでした。

					//個別のfruitsインスタンスの生成(これ忘れるとヌルポ)
					fruits[i] = new FruitData();
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?