gpt4 book ai didi

Java - 从文件中读取有符号整数

转载 作者:行者123 更新时间:2023-12-02 07:53:38 24 4
gpt4 key购买 nike

我试图将文件中的 10 个有符号整数读入数组,但由于某种原因,它没有发生,并且在编译和运行时我没有收到任何错误。我只是想要第二双眼睛来看看这个,看看我可能错过了什么。

测试文件为“input.txt”,包含:-1, 4, 32, 0, -12, 2, 30, 1, -3, -32

这是我的代码:

  public void readFromFile(String filename)
{
try {
File f = new File(filename);
Scanner scan = new Scanner(f);
String nextLine;
int[] testAry = new int[10];
int i = 0;

while (scan.hasNextInt())
{
testAry[i] = scan.nextInt();
i++;
}
}
catch (FileNotFoundException fnf)
{
System.out.println(fnf.getMessage());
}
}

最佳答案

您在 Scanner 对象上使用默认分隔符。

尝试使用 useDelimiter(\\s*,\\s*") 行中的分隔符。它的正则表达式用逗号分隔文件中的输入。


try {
File f = new File("input.txt");
Scanner scan = new Scanner(f);
scan.useDelimiter("\\s*,\\s*");
String nextLine; //left it in even tho you are not using it
int[] testAry = new int[10];
int i = 0;

while (scan.hasNextInt()) {
testAry[i] = scan.nextInt();
System.out.println(testAry[i]);
i++;
}
} catch (FileNotFoundException fnf) {
System.out.println(fnf.getMessage());
}

关于Java - 从文件中读取有符号整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9917948/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com