1

当导入的文件包含 100 个或更多数字时,我的以下代码有效。如果文件中剩余的数字少于 100 个,如何让循环停止?当数字少于 100 个时,由于数组未满而出现错误。

try {
    Scanner in = new Scanner(new File(filename));
    int[] aNums = new int[100];
    System.out.print("Array contents: ");
    int i =0;
    while (i < aNums.length){
        generated = in.nextInt() ;
        aNums[i] = generated;
        System.out.print( aNums[i] );
        System.out.print(" ");
        i++;
    }
    System.out.println(" ");
    System.out.println(" ");
    System.out.print("Array contents: ");
    for (i = aNums.length - 1; i >= 0; i--) {
        System.out.print( aNums[i] );
        System.out.print(" ");
    }
}
// Catch block, needed when using file input
catch (FileNotFoundException e) {
    System.out.println("That file was not found. Program terminating...");
    e.printStackTrace();
}
4

3 回答 3

2

如果文件有更多值,只需检查扫描仪:

while (i < len && in.hasNextInt())
于 2013-02-07T22:07:21.103 回答
0

试试这个

File file = new File(filename);
Scanner in = new Scanner(file);
int[] aNums = new int[file.length()];

我没试过。。希望有效

于 2013-02-07T22:23:43.317 回答
0

试试这个:

List<Integer> integerList = new ArrayList<Integer>();

while(in.hasNextInt()) {
  integerList.add(in.nextInt());
}
int totalNum = integerList.size();
for(int i = 0; i < 100 && totalNum - i > 100; i++) {
   aNums[i] = integerList.get(i);
}
于 2013-02-07T23:02:55.467 回答