嘿伙计我对java很新,我在尝试将一个名为compact.txt的文件中的数字添加到数组中时遇到了这个问题。到目前为止,这是我的代码:
public void compactArray(){
try{
Scanner scan = new Scanner(new File("compact.txt"));
while(scan.hasNextInt()){
num++;
}
int [] a = new int[num];
Scanner in = new Scanner(new File("compact.txt"));
while(counter < num){
a[counter] = in.nextInt();
counter++;
}
System.out.println(Arrays.toString(a));
}catch(IOException bob){
bob.getMessage();
}
}
此代码的问题在于它永远不会停止运行。首先,我的代码读取compact.txt,然后计算它有多少数字来计算数组的大小。然后我创建另一个扫描程序变量,将compact.txt中的数字添加到数组中。我使用计数器变量作为在数组a中添加所需数量的数字时停止的方法。我不太清楚问题是什么,但它继续运行,并没有到达应该打印出阵列的行。有人可以帮帮我吗。非常感谢你。
答案 0 :(得分:5)
你应该致电
scan.nextInt();
在你的第一个循环中。你永远不会移动你的光标,因此你继续阅读第一个元素。
但是,您的解决方案需要在数据集中进行两次。您可能希望使用ArrayList,这是一个可以调整大小的数组。这样,您就不需要先计算文件了。
答案 1 :(得分:1)
你在那里做错了:你应该只使用一个Scanner
对象。
更具体地说,在您的情况下出现的问题如下:您正在检查扫描程序是否在while(scan.hasNextInt()){
中有下一个int,但您实际上从未读过该int。所以它将永远循环。
正确的工作代码是:
public void compactArray(){
List<Integer> ints = new ArrayList<>();
try{
Scanner scan = new Scanner(new File("compact.txt"));
while(scan.hasNextInt()){
ints.add(in.nextInt());
}
}catch(IOException ex){
ex.getMessage();
}
System.out.println(Arrays.toString(ints.toArray(new int[ints.size()])));
}
我还更改了代码的以下几点:
List<Integer>
来存储整数。因为这个,不需要再计算了!System.out.println
中,现在首先将List<Integer>
转换为数组,然后提供String
- 表示。答案 2 :(得分:0)
变化
while(scan.hasNextInt()){ here is the problem, This loop never move to next integer. You need to call to scan.nextInt() required to move next integer
num++;
}
到
while(scan.hasNextInt()){
scan.nextInt();
num++;
}