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

标签 java

基本上,我使用名为 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 位小数的 double 。一旦我更改为 hasNextDouble(),程序就按预期运行。

关于java - 从文本文件读取并将字符串更改为要在数组中输入的整数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43174800/

相关文章:

Java - REGEX 构造

java - 从主 Java 调用方法

java - 使用 HtmlUnit 保存完整页面时文本被截断

java - struts2 中没有调用操作类的方法

java - FutureTask 取消()

java - Play Framework CSRF 错误 "[CSRF] Check failed because no token found in headers"

java - 更新ListView过程中AsyncTask错误

java - 如何测试任何方法调用是否抛出异常?

java - rxjava 当超时时跳过项目并继续下一个项目

java - Spring MVC 应用程序中的 UTF8 转换错误