【发布时间】:2017-12-07 06:37:58
【问题描述】:
因此,对于我的计算机科学课,我们必须创建一个程序,该程序将从名为“compact.txt”的文本文件中读取数据,并将其中的整数存储到 int[] 中。之后,我们必须将数字打印到终端,文本文件中包含 0,然后文本文件中不包含 0。代码编译并运行,但是当它运行时它不会向终端打印任何内容,它会完全冻结所有 BlueJ。冻结后,我什至无法从主目录中复制代码,不得不从任务管理器中强制关闭它。 FileInput 是我的班级用来读取文件的。这是我的代码:
import chn.util.*;
public class compact
{
public static void main(String [] args)
{
FileInput fI = new FileInput("compact.txt");
int[] ar = new int[100];
String line = fI.readLine();
fI.close();
System.out.println(line);
int count = 0;
int x = 0;
while(x < line.length())
{
if(!line.substring(x, x+1).equals(" "))
{
if(!line.substring(x + 1, x + 2).equals(" ") && !
(line.length() - 1 == x))
{
ar[count] = Integer.parseInt(line.substring(x + 1, x+2));
}
else
{
ar[count] = Integer.parseInt(line.substring(x, x+1));
}
count++;
}
x++;
}
System.out.print("Before: " + ar[0]);
for(int i = 1; i < count; i++)
{
System.out.print(", " + ar[i]);
}
System.out.print("\n");
System.out.println("After: ");
for(int i = 0; i < count; i++)
{
if(ar[i] == 0)
{
System.out.print("");
}
else
{
if(i == count - 1)
{
System.out.print(ar[i]);
}
System.out.print(ar[i] + ", ");
}
}
}
}
这就是“compact.txt”文件中包含的内容:
0 6 13 0 0 75 33 0 0 0 4 29 21 0 86 0 32 66 0 0
【问题讨论】:
-
所以,我得到一个
StringIndexOutOfBoundsException,因为当x等于line.length() - 1、x + 1或x + 2时,超出了String的长度。事实上,更简单的方法可能是使用String#split或Scanner并从流中读取每个字符