如果他输入 char/string 而不是数字,如何询问用户是否想重新启动程序?

How to ask user if he wants to start program all over again if he typed a char/string instead of a number?

我是新来的,也是 Java 的新手,大约 1-2 周前开始,我想制作一个应用毕达哥拉理论的应用程序。全部完成,但现在我被困在一个地方,如果他输入字符或字符串而不是数字,我希望询问用户是否想再试一次,重新开始。

我做错了什么?这是我的代码,我也添加了注释,这样如果您不理解我想要实现的目标,它会更容易。

提前致谢!

package pitagoracalculator;
import java.util.Scanner;

public class PitagoraCalculator {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
            double nr1;
            double nr2;
            double ipot;
            boolean raspuns;
            String raspuns1;

            do{
                try{
                    //user is asked for first number
                    System.out.print("Introduceti primul numar: ");
                    nr1 = input.nextDouble();

                    //user is asked for second number
                    System.out.print("Introduceti al 2-lea numar: ");
                    nr2 = input.nextDouble();

                    //result of calculation
                    ipot = (nr1*nr1)+(nr2*nr2);
                    System.out.println("Rezultatul este: "+ipot+"^2");

                //in case user inserts a string/char instead of a double => error
                } catch (Exception e){
                    System.err.println("Nu ati introdus un numar.");
                    break;
                }

                //user is asked if he wants to do another calculation
                System.out.println("Doriti sa faceti un alt calcul? (da/nu)");
                raspuns1 = input.next();

                //if his answer is yes, raspuns = true, else raspuns = false
                if(raspuns1.equalsIgnoreCase("da"))
                    raspuns = true;
                else{
                    System.out.println("La revedere!");
                    raspuns = false;
                }

            //checks if the answer was true or false
            }while(raspuns == true);
    }
}

替换

//in case user inserts a string/char instead of a double => error
} catch (Exception e){
   System.err.println("Nu ati introdus un numar.");
   break;
}

//in case user inserts a string/char instead of a double => error
} catch (Exception e){
   System.err.println("Nu ati introdus un numar.");
   //clear pending input.
   if (input.hasNext()) {
        input.next();
   }
   continue;
}

"break"退出循环,"continue"继续下一个循环。

您还必须使用 true

初始化 raspuns 变量
boolean raspuns = true;

你可以在例外情况下调用方法 case.For 你应该在同一个 class 中创建一个方法并将你所有的东西放在那个方法中使用 if-else 循环..