1

我已经有 2 年多没有编码了,而且非常生疏,但是在谷歌上搜索了一段时间后,我无法弄清楚我做错了什么。首先我会解释这个程序,即使它很简单。我有一个 .txt 文件,其中包含 680 个数字,每行一个数字,并试图找到范围为 000-999 的数字的频率。我相信我可以弄清楚频率部分,因为它看起来很基本,但是我无法弄清楚如何从 .t​​xt 文件中导入数字。这是我遇到的错误:

C:\Users\Arthur\Documents\FrequencyStraightPlay\FrequencyStraightPlay.java:17: error: variable sc might not have been initialized
        while (sc.hasNextInt()) {
               ^
1 error

编码:

import java.io.*;
import java.util.*;

public class FrequencyStraightPlay {

public static void main(String[] args) {

    int [] rawNumbers = new int [680];
    int i = 0;

    Scanner sc;
    try {
        sc = new Scanner(new File("Numbersnospaces.txt"));
    } catch (FileNotFoundException e) {
        System.out.println("File not Found!");
    }
    while (sc.hasNextInt()) {
        rawNumbers[i++] = sc.nextInt();
    }

    System.out.println("The Raw Numbers: ");

    for (i = 0; i < 680; i++) {
        System.out.println(rawNumbers[i]);
    }

}

}
4

3 回答 3

8

如果你 catch FileNotFoundException,那么sc就不会被初始化。

while循环放在try块内,这样你就知道sc在你到达它的时候已经初始化了。

有人可能认为解决方案是在声明时初始化scnull但这是不正确的,因为不移动块while内的循环,如果你抓住 a ;try你可能会得到 a 还是会。NullPointerExceptionFileNotFoundExceptionscnull

于 2013-04-09T17:21:15.710 回答
0

您需要处理找不到文件的情况。考虑抛出异常(或返回)而不是继续代码。

于 2013-04-09T17:21:27.347 回答
0

如果 try catch 块中的代码抛出异常,则 sc 的值为 null。一旦你发现异常,你不应该继续 sc.hasNextInt() 。

try {
        sc = new Scanner(new File("Numbersnospaces.txt"));
    } catch (FileNotFoundException e) {
        System.out.println("File not Found!");
        return; // this will remove that error/warning
    }
于 2013-04-09T17:22:05.347 回答