java - 如果在循环的迭代过程中输入了无效的输入,我如何让循环在其当前迭代中重新开始
问题描述
我是编程新手,正在处理用户命名文件的 Java 任务。然后将该文件传递给用户写入测试成绩的方法,然后传递给另一个方法以读取和显示具有班级平均水平的测试成绩。
我目前正在研究将学生成绩写入我已成功完成的文件的方法,但如果输入了非数值,我需要实施错误检查。我对 InputMismatchException 使用了带有 try 和 catch 的 while 循环,有时该循环可以工作。如果在循环第一次迭代中输入了无效输入,它将捕获并重复,但是如果在除第一次之外的任何其他迭代中输入无效输入,它将捕获 InputMismatchException,但它也会跳出循环并继续到下一个方法。我如何让循环从无效循环的迭代开始。我会很感激任何帮助,如果我的代码写得不好,我很抱歉,因为我对编程很陌生。
这是我正在研究的方法:
public static void inputScores(String newFile)
{
Scanner scan = new Scanner(System.in);
Formatter write;
try
{
write = new Formatter(newFile +".txt");
double score = 0.0;
int count = 1;
boolean again = false;
while(!again){
try
{
while(score >= 0)
{
System.out.print("Please enter student " + count + "'s test score, input -1 to quit:\n>");
score = scan.nextDouble();
again = true;
count++;
if(score >= 0)
{
write.format("%.2f%n", score);
}
else if(score <= -1)
{
break;
}
}
}
catch(InputMismatchException ex){
System.out.println("Invalid input, Student's scores must be a number");
scan.next();
}
}
write.close();
}
catch(FileNotFoundException e)
{
System.out.println(e.getMessage());
}
}
解决方案
试试这个代码。希望这将满足您的要求。
public static void inputScores(String newFile) {
Scanner scan = new Scanner(System.in);
Formatter write=null;
try {
write = new Formatter(newFile + ".txt");
double score = 0.0;
int count = 1;
while(true) {
try {
System.out.println("Please enter student " + count + "'s test score, input -1 to quit:\n>");
score = scan.nextDouble();
count++;
if(score>=0)
write.format("%.2f%n", score);
else
break;
}catch (InputMismatchException e) {
System.err.println("Invalid input, Student's scores must be a number");
scan.next();
System.out.println();
}
}
write.close();
scan.close();
}
catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
}
推荐阅读
- java - 如何在java中安排动态任务
- mysql - 查询中有多个 LIKE 语句
- android - Android List with a bigger item in the middle
- html - 如何将文本参数与谷歌字体 API 一起用于一种字体类型
- spring-webflux - Spring Reactor onErrorContinue not working
- reactjs - 如何部署像 Sizzy 这样的电子应用程序的构建?
- javascript - 在扩展表 HTML 中创建单元格名称
- java - 仅当 if 语句之一运行时才执行代码
- javascript - 如何在我的网站上向 Google 地图小部件添加用户输入标记,并从中获取纬度和经度数据?
- docker - Catching SIGTERM from alpine image