我没有编写超过2年的编码而且非常生疏,但是在google上玩了很长一段时间后我无法弄清楚我做错了什么。首先,我会解释这个程序,即使它非常简单。我有一个包含680个数字的.txt文件,每行一个数字,我试图找到范围为000-999的数字频率。我相信我可以弄清楚频率部分,因为它看起来非常基本,但我无法弄清楚如何从.txt文件中导入数字。这是我的错误:
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]);
}
}
}
答案 0 :(得分:8)
如果您抓住FileNotFoundException
,则sc
将不会被初始化。
将while
循环放在try
块内,以便您知道{J}已经初始化{。}}。
有人可能会认为解决方案是在声明sc
时初始化sc
,但这是不正确的,因为没有移动null
块内的while
循环,如果你抓到try
,你可以获得NullPointerException
; FileNotFoundException
仍为sc
。
答案 1 :(得分:0)
您需要在找不到文件时处理此案例。考虑抛出异常(或返回)而不是继续代码。
答案 2 :(得分: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
}