如果在循环迭代期间输入了无效输入,我如何让循环在当前迭代中再次开始

If an invalid input is entered during an iteration of a loop, how do I get the loop to start again at its current iteration

我是编程新手,正在处理一个 Java 作业,其中用户命名一个文件。然后该文件被传递给用户写入测试成绩的方法,然后传递给另一个方法来读取和显示具有 class 平均水平的测试成绩。

我目前正在研究将学生成绩写入文件的方法,我已成功完成,但如果输入非数值,我需要实施错误检查。我对 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());
    }      
}  

Try this code. Hope this will fulfill your requirement.

    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());
        }
    }