【问题标题】:How to fix loop while/try catch error in java如何在java中修复循环while/try catch错误
【发布时间】:2019-08-09 19:07:16
【问题描述】:

我正在创建一个简单的计算器程序(这个 java 编程的第一周)。

问题背景:只有 5 个选项有效。 (1-加法;2-减法;3-乘法;4.除法;5.退出)。当用户输入 1-4 选项时,将填充结果,但用户需要循环返回以重新输入数据,直到选择了选项 5。 5是退出程序(结束循环/程序的唯一方法)。我的问题: 1. 如何阻止 try-catch 不停地运行?有没有更好的方法来实现 try-catch?例如,处理字符串数据错误消息。理想情况下,如果输入字符串,代码应该循环返回以通过生成消息“请重新输入数字...”再次重新启动,直到用户输入有效数字 2. 我正在尝试在主类中使用尽可能多的静态方法。我不确定我的做法是否准确?

这是我输入的代码:

    12 2 
    //-everything works well.
    2 //-enter again 
    s s (string entry-error) 

然后,将填充以下消息:

    "You have entered invalid floats. please re-enter:  
    Exception in thread "main" java.util.InputMismatchException
        ...
        at calculator.performSubtract(calculator.java:65)
        at calculator.main(calculator.java:34)" 

代码(示例)

   public class calculator {
//use static methods to implement the program 
    static Scanner userInput = new Scanner(System.in);
    static int userChoice;
    static float numberOne;
    static float numberTwo; 
    static float answer; 
    static int choice;

    public static void main(String[] args) {
       do {
       //this menu statement has to be repeated unless 5 is entered (exit the 
      //program) 
        System.out.println("Welcome to <dj's> Handy Calculator\n\n\t \1. Addition \n\t 2. Subtraction\n\t 3. Multiplication\n\t 4. Division\n\t 5. Exit\n\n");
        System.out.print("What would you like to do? ");

        try {   
        choice = userInput.nextInt();
        }catch (InputMismatchException e) {
            continue;
        }
        switch (choice) {
        case 2: performSubtract();
        break;
        ...
        case 5: exit();
        break;
        } 
        }while(choice >0 && choice <5);
        userInput.close();
    }

    public static void performSubtract () {
        //catch error statement. 
        try {
        numberOne = userInput.nextFloat();
        numberTwo= userInput.nextFloat();
        answer= numberOne-numberTwo;
        } catch (Exception e) {
        System.out.println("You have entered invalid floats. please re-enter:  ");
        numberOne = userInput.nextFloat();
        numberTwo= userInput.nextFloat();
        }
        System.out.printf("Please enter two floats to subtraction, separated by a space: %.1f %.1f\n", numberOne, numberTwo);
        System.out.printf("Result of subtraction %.1f and %.1f is %.1f\n", numberOne, numberOne, answer);
        System.out.println("\nPress enter key to continue...");
    }

}

【问题讨论】:

  • 看起来你的帖子主要是代码。请添加更多详细信息,并将代码缩减为minimal reproducible example
  • 谢谢。仍在努力学习如何简洁地提出问题。我正在学习java。对所有不同的概念有点不知所措。

标签: java loops try-catch


【解决方案1】:

我认为问题在于您没有从扫描仪中清除问题令牌。 您的 catch 语句会打印一条错误消息,然后再尝试将相同的标记解析为 int 或 float。

您可以在这里查看:https://www.geeksforgeeks.org/scanner-nextint-method-in-java-with-examples/

看来您需要调用 userInput.next() 才能越过无效令牌。

此外,如果您愿意,hasNextInt() 可以让您完全避免遇到问题。

【讨论】:

    【解决方案2】:

    您的错误在于Scanner.nextFloat 在读取无效输入时不会推进当前令牌。这意味着当您在 catch 语句中再次调用 nextFloat 两次时,您将再次读取标记 ss,其中第一个将导致再次抛出 InputMismatchException。您应该将 performSubtract 方法更改为如下所示:

    public static void performSubtract () {
        //catch errors
        System.out.println("Please enter two floats to subtraction, separated by a space");
        userInput.nextLine();//ignore the new line
        do {
            try {
                String[] nextLineTokens = userInput.nextLine().split("\\s+");
                if(nextLineTokens.length != 2)
                {
                    System.out.println("You have not entered two floats. please re-enter:");
                    continue;
                }
                numberOne = Float.parseFloat(nextLineTokens[0]);
                numberTwo = Float.parseFloat(nextLineTokens[1]);
                answer= numberOne-numberTwo;
                break;
            }
            catch (Exception e) {
                System.out.println("You have entered invalid floats. please re-enter:  ");
            }
        } while (true);
        System.out.printf("You entered: %.1f %.1f\n", numberOne, numberTwo);
        System.out.printf("Result of subtraction %.1f minus %.1f is %.1f\n", numberOne, numberTwo, answer);
        System.out.println("\nPress enter key to continue...");
        userInput.nextLine();
    }
    

    此外,如果您输入了无效的输入,您的解析代码将继续,但如果您输入的数字不是 1-5,则会退出。如果这是您第一次读入输入,则代码也会因无效输入而退出。你可能应该改变你的解析迭代循环:

    public static void main(String[] args) {
        while(choice != 5) {
            //this menu statement has to be repeated unless 5 is entered (exit the 
            //program) 
            System.out.println("Welcome to <dj's> Handy Calculator\n\n\t 1. Addition \n\t 2. Subtraction\n\t 3. Multiplication\n\t 4. Division\n\t 5. Exit\n\n");
            System.out.print("What would you like to do? ");
    
            try {   
                choice = userInput.nextInt();
            }
            catch (InputMismatchException e) {
                userInput.next();
                continue;
            }
            switch (choice) {
                case 2: performSubtract();
                break;
                // ...
                case 5: exit();
                break;
            } 
        }
        userInput.close();
    }
    

    【讨论】:

      【解决方案3】:

      对于第一个问题:try-catch 块通常用于查看您的代码是否运行无误。通过你解释你想要做什么,我会在分配 numberOnenumberTwo 之前使用一个while循环,无论输入是否浮动:

      // pseudo
      
      while(input != float || input2 != float)
      {
        print(please reenter)
      }
      numberOne = input
      numberTwo = input2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-24
        • 2014-09-11
        • 1970-01-01
        • 2017-10-09
        相关资源
        最近更新 更多