gpt4 book ai didi

java - 从txt文件中读取整数并存储到数组中

转载 作者:行者123 更新时间:2023-12-01 18:37:28 25 4
gpt4 key购买 nike

我在仅从文本文件读取和存储整数时遇到问题。我使用的是 int 数组,所以我想在没有列表的情况下执行此操作。我收到输入不匹配异常,但我不知道应该如何纠正该问题。正在读取的文本文件还包括字符串。

  public static Integer[] readFileReturnIntegers(String filename) {
Integer[] array = new Integer[1000];
int i = 0;
//connect to the file
File file = new File(filename);
Scanner inputFile = null;
try {
inputFile = new Scanner(file);
}
//If file not found-error message
catch (FileNotFoundException Exception) {
System.out.println("File not found!");
}
//if connected, read file
if(inputFile != null){
System.out.print("number of integers in file \""
+ filename + "\" = \n");
//loop through file for integers and store in array
while (inputFile.hasNext()) {
array[i] = inputFile.nextInt();
i++;
}
inputFile.close();
}
return array;
}

最佳答案

您可以使用类似的东西(跳过任何非整数),并且您应该关闭您的扫描仪!

// if connected, read file
if (inputFile != null) {
System.out.print("number of integers in file \""
+ filename + "\" = \n");
// loop through file for integers and store in array
try {
while (inputFile.hasNext()) {
if (inputFile.hasNextInt()) {
array[i] = inputFile.nextInt();
i++;
} else {
inputFile.next();
}
}
} finally {
inputFile.close();
}
// I think you wanted to print it.
System.out.println(i);
for (int v = 0; v < i; v++) {
System.out.printf("array[%d] = %d\n", v, array[v]);
}
}

关于java - 从txt文件中读取整数并存储到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21300584/

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