gpt4 book ai didi

java - 为什么我的错误检查不起作用?

转载 作者:行者123 更新时间:2023-12-03 08:55:24 25 4
gpt4 key购买 nike

我所做的是,我进行了一次错误检查,每次用户输入无效的文件名时都会循环遍历:

    public static Scanner readFile(String filename){
Scanner stdin = new Scanner(System.in);
File input = new File(filename);
Scanner sc = null;
do {
try {
sc = new Scanner(input);
}
catch(FileNotFoundException e) {
System.out.println("Filename not valid. Please try again:");
filename = stdin.nextLine();
}
} while (!new File(filename).exists());
return sc;
}

我也有足够的方法来读取该文件并将数据放入数组中:
public static CO2Data[] readData(String filename){
File input = new File(filename);
Scanner sc = null;
try{
sc = new Scanner(input);
}
catch(FileNotFoundException e){
System.out.println("Filename not valid");
System.exit(-1);
}
String info = sc.nextLine();
int total = sc.nextInt();
CO2Data[] arr = new CO2Data[total];
for(int i=0; i<10;i++){
arr[i] = new CO2Data();
}
for(int i=0; i<10;i++){
arr[i].setCountry(sc.next());
arr[i].setTotalCO2(sc.nextDouble());
arr[i].setRoadCO2(sc.nextDouble());
arr[i].setCO2PerPerson(sc.nextDouble());
arr[i].setCarsPerPerson(sc.nextInt());
}
return arr;
}

问题是,如果我先输入一个无效的文件名然后输入一个有效的名称,则程序会说该文件无效,但是如果我先输入一个有效的文件名,则该程序可以正常工作。因此,键入有效的文件名首先可以正常工作,但是键入无效的名称然后输入有效的名称会使程序给我一条错误消息。

最佳答案

好吧,让我们遍历整个场景:

如果输入的文件名无效,则代码将移至catch块,等待您在该行中输入新的文件名
filename = stdin.nextLine();
您输入有效的文件名,变量文件名将重置为新文件名(到目前为止很好)

然后,我们继续到While块,它将检查文件是否存在(确实存在!),因此,我们移到return语句(包含问题)。

在return语句中,您返回持有先前无效的文件名的扫描仪。返回新文件之前,您需要使用新文件重新制作扫描仪。

我可能会编辑while循环以阅读

public static Scanner readFile(String filename){
Scanner stdin = new Scanner(System.in);
File input = new File(filename);
Scanner sc = null;
do {
try {
input = new File(filename);
sc = new Scanner(input);
}catch(FileNotFoundException e) {
System.out.println("Filename not valid. Please try again:");
filename = stdin.nextLine();
}
} while (!input.exists());
return sc;
}

这样,我们在收到有效输入后创建一个新的 File类,然后返回一个保存了新 Scanner的新 input

关于java - 为什么我的错误检查不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27323805/

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