[英]Error part of loading array from text file does not work correctly
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class readfile{
static int[] array1 = new int[5];
public static int[] choosefile(){
try {
Scanner s = new Scanner(new File("input.txt"));
int i = 0;
while (s.hasNext()) {
array1[i++] = s.nextInt();
}
s.close();
} catch (FileNotFoundException e) {
System.err.println("The file does not exist!");
}
return array1;
}
readfile(int[] array1) {
readfile.array1 = array1;
}
void printarray() {
System.out.println("Datas in the array");
System.out.println(Arrays.toString(array1));
System.out.println();
}
Basically the code works if the text file exists but if it doesnt the output is like基本上,如果文本文件存在,则代码有效,但如果它不存在,则 output 就像
The file does not exist, Datas in the array [0, 0, 0, 0, 0]文件不存在,数组中的数据 [0, 0, 0, 0, 0]
It says "The file does not exist."它说“文件不存在”。 but still do other operations with an array whichs all values are 0?
但是仍然对所有值为0的数组进行其他操作? How can I fix it?
我该如何解决?
You return after the try catch .你在try catch之后返回。 Meaning it hits the catch and then returns array1.
这意味着它击中了捕获然后返回array1。 To fix this, you can return inside the catch.
要解决此问题,您可以返回内部捕获。
} catch (FileNotFoundException e) {
System.err.println("The file does not exist!");
//return here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.