在下面的代码中,构造函数没有初始化 numFile Scanner。我将构造函数的内容添加到 main 方法中以使其工作。如果我不这样做,则会抛出 java.lang.NullPointerException 。有人介意解释一下原因吗?另外,我需要在构造函数上抛出 IOException 吗?
感谢您提供任何有用的建议。
托尼
import java.io.*;
import java.util.Scanner;
public class CountPositiveIntegers {
static Scanner numFile;
static String fileName; // the name of the file in which the integers are stored
static int number; // holds the current number being read
static int counter; // a counter used to sum the number of positive integers
public CountPositiveIntegers() throws IOException {
fileName ="D:\\Java\\Source\\numFile.dat";
System.out.println("File Name: " + fileName);
numFile = new Scanner(new FileReader(fileName));
number = 0;
counter = 0;
}
public static void main(String[] args) throws FileNotFoundException {
// numFile is not being initializing in the constructor
fileName = "D:\\Java\\Source\\numFile.dat";
numFile = new Scanner(new FileReader(fileName));
number = 0;
counter = 0;
if (numFile.hasNext()) { // check to see if there are any values in the file
while (numFile.hasNextInt()) { // reads in integers
number = numFile.nextInt();
if (number % 2 == 0 & number != 0) {
counter++;
}
}
numFile.close(); // close the file
// print to screen the number of even integers stored in the file
System.out.println("There are " + counter
+ " even numbers in this file");
} else {
System.out.println("The file is empty.");
}
System.exit(0); // cleanly exit the program
}
}
最佳答案
您必须显式调用构造函数才能使其工作。 (您永远不会创建一个new CountPositiveIntegers()
)。
关于java - 构造函数未初始化 Scanner 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8981886/