从文本文件中读取并将字符串更改为要在数组中输入的 int 不起作用



基本上,我使用一种名为CS160Input(由我的教师提供(的方法询问文件名。文本文档有一堆条目,每个条目都在各自的行上,我试图将每个数字分配给数组中的一个位置,但我未能实际写入数组。我知道它正在查找文件,因为当我打印出计数器时,它会告诉我文件中正确的行数。但是当我尝试打印出数组中的一个位置时,我尝试了索引 3,正如您在代码中看到的那样,无论我尝试什么,它都会给我 0。我首先尝试创建一个字符串数组,最终每个索引值也为 null。

public static void caclulate() throws FileNotFoundException {
        String fileName = CS160Input.readString("Please enter the name of the file: ");
        Scanner sc = new Scanner (new File (fileName));
        int value, counter = 0;
        int array[] = null;
        while (sc.hasNextLine()) {
            sc.nextLine();
            counter++;
        }
        Scanner scanner = new Scanner(new File(fileName));
        int[] calcArray = new int [counter];
        int i = 0;
        while(scanner.hasNextInt()){
           calcArray[i++] = scanner.nextInt();
        }
        System.out.println(calcArray[3]);
        System.out.println(counter);
    }

感谢@Gendarme指出如果两者之间有值,hasNextInt(( 可能会吐出 false,这让我仔细看看,我意识到在以前的程序中,写入文本文件的数字是小数点后 2 位的双精度。一旦我更改为hasNextDouble((,程序就按预期工作。

最新更新