java - 构造函数未初始化 Scanner 对象

标签 java

在下面的代码中,构造函数没有初始化 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/

相关文章:

java - Heroku 上的 Spring Boot Gradle 应用程序 : Unable to access jarfile

java - SceneBuilder 坐标与 JavaFX 坐标

java - 您如何在 Bootstrap 文件中正确设置不同的 Spring 配置文件(让 Spring Boot 以不同的云配置服务器为目标)?

java - java中的多线程,等待困难

java - 如何将 TestNG 与 Java Play 2.4.x 一起使用?

java - 通过UDP发送图片

java - PooledConnectionFactory 处于无限重新连接循环中

java - 使用Java错误绘制六边形

java - 使用替代方法重载方法值 toString

java - int binarySearch 数组列表