如果用户输入不是java中正确的数据类型,则给出错误消息并重新启动循环,如果是,则继续?

如果用户输入不是java中正确的数据类型,则给出错误消息并重新启动循环,如果是,则继续?,java,switch-statement,java.util.scanner,mismatch,Java,Switch Statement,Java.util.scanner,Mismatch,嘿,这是我计划的一小部分,我有大问题。如果输入不是整数,我希望程序给用户一条错误消息,并从一开始就启动循环,如果输入是整数,我希望程序继续进入开关/案例。这是我到目前为止得到的结果,但它不起作用,因为如果输入不正确,我会得到inputmismatchexception,如果输入正确,它不会继续到开关/案例中 public static void main(String[] args) { ArrayList<Dog> doglist = new ArrayList<Do

嘿,这是我计划的一小部分,我有大问题。如果输入不是整数,我希望程序给用户一条错误消息,并从一开始就启动循环,如果输入是整数,我希望程序继续进入开关/案例。这是我到目前为止得到的结果,但它不起作用,因为如果输入不正确,我会得到inputmismatchexception,如果输入正确,它不会继续到开关/案例中

public static void main(String[] args) {
    ArrayList<Dog> doglist = new ArrayList<Dog>();
    Scanner myscan = new Scanner(System.in);
    boolean running = true;

    while (running) {
        System.out.println("\n************************************");
        System.out.println("\nWelcome to the kennel club!");
        System.out.println("\n************************************");
        System.out.println("\n[1] Register new dog");
        System.out.println("[2] Print out list");
        System.out.println("[3] Increase age");
        System.out.println("[4] Remove dog");
        System.out.println("[5] Quit program");
        System.out.println("\n************************************");
        System.out.println("\nChoose: ");

        int option = 0;
        boolean inputOk = false;
        do {
            try {
                option = myscan.nextInt();
                inputOk = true;
            } catch (InputMismatchException e) {
                System.out.println("Option must be a number");
                myscan.nextLine(); // to consume the \n that remains at the end of the line after using nextInt();
            }
        }
        while (!inputOk);

        switch (option) {
            case 1:
                System.out.println("Write name:");
                String name = myscan.next();
                System.out.println("Write race:");
                String race = myscan.next();
                System.out.println("Age:");
                int age = myscan.nextInt();
                System.out.println("Weight:");
                double weight = myscan.nextDouble();

                Dog dog = new Dog(name, race, age, weight);

                doglist.add(dog);

                break;

            case 2:

                System.out.println("Minimum length of tail:");
                double userInput1 = myscan.nextDouble();

                for (Dog d : doglist) {
                    if (d.getTailLength() >= userInput1) {
                        System.out.println(d.toString());
                    }
                }

                break;

            case 3:

                System.out.println("Name of dog:");
                String userInput2 = myscan.next();
                int flag = 0;
                for (Dog d : doglist) {
                    if (d.getName().equals(userInput2)) {
                        d.increaseAge();
                        d.increasetailLength();
                        flag = 1;
                        break;
                    }
                }

                if (flag == 0) {
                    System.out.println("Error, can't find dog with name:" + userInput2);
                }

                break;

            case 4:

                System.out.println("Name of dog:");
                String userInput3 = myscan.next();

                Dog dogToRemove = null;

                for (Dog d : doglist) {
                    if (d.getName().equals(userInput3)) {
                        dogToRemove = d;
                        System.out.println("Dog is removed");
                    }
                }

                if (dogToRemove == null) {
                    System.out.println("Error, can't find dog with name: " + userInput3);
                } else {
                    doglist.remove(dogToRemove);
                }

                break;

            case 5:

                running = false;//Avslutar loopen och därmed programmet
                System.out.println("Program finshed");
                break;

            default:

                System.out.println("Error, choose between [1] [2] [3] [4] [5]");//Felmeddelande om valet är någon annan siffra än de som menyn innehåller
                break;
        }
    }
}
publicstaticvoidmain(字符串[]args){
ArrayList doglist=新的ArrayList();
Scanner myscan=新扫描仪(System.in);
布尔运行=真;
(跑步时){
System.out.println(“\n*******************************************”);
System.out.println(“\n欢迎来到犬舍俱乐部!”);
System.out.println(“\n*******************************************”);
System.out.println(“\n[1]注册新狗”);
System.out.println(“[2]打印列表”);
System.out.println(“[3]增加年龄”);
System.out.println(“[4]删除狗”);
System.out.println(“[5]退出程序”);
System.out.println(“\n*******************************************”);
System.out.println(“\n选择:”);
int选项=0;
布尔inputOk=false;
做{
试一试{
option=myscan.nextInt();
inputOk=true;
}捕获(输入不匹配异常e){
System.out.println(“选项必须是数字”);
myscan.nextLine();//在使用nextInt()后,使用行末尾的\n;
}
}
而(!inputOk);
开关(选件){
案例1:
System.out.println(“写入名称:”);
String name=myscan.next();
System.out.println(“Write race:”);
字符串race=myscan.next();
System.out.println(“年龄:”);
int age=myscan.nextInt();
系统输出打印项次(“重量:”);
双重重量=myscan.nextDouble();
狗=新狗(名称、种族、年龄、体重);
添加(狗);
打破
案例2:
System.out.println(“尾巴的最小长度:”);
double userInput1=myscan.nextDouble();
用于(狗d:狗名单){
如果(d.getTailLength()>=userInput1){
System.out.println(d.toString());
}
}
打破
案例3:
System.out.println(“狗的名字:”);
字符串userInput2=myscan.next();
int标志=0;
用于(狗d:狗名单){
如果(d.getName().equals(userInput2)){
d、 增加();
d、 增加尾长();
flag=1;
打破
}
}
如果(标志==0){
System.out.println(“错误,找不到名为“+userInput2”的狗);
}
打破
案例4:
System.out.println(“狗的名字:”);
字符串userInput3=myscan.next();
Dog dogToRemove=null;
用于(狗d:狗名单){
如果(d.getName().equals(userInput3)){
dogToRemove=d;
System.out.println(“狗被移除”);
}
}
if(dogToRemove==null){
System.out.println(“错误,找不到名为“+userInput3”的狗);
}否则{
删除(dogToRemove);
}
打破
案例5:
running=false;//Avslutar loopen och därmed programmet
System.out.println(“程序已完成”);
打破
违约:
System.out.println(“错误,在[1][2][3][4][5]之间选择”);//Felmeddelande om valetär någon annan siffraän de som menyn innehåller
打破
}
}
}

您可以添加do while来读取捕获输入不匹配异常的选项:

int option = 0;
boolean inputOk = false;
do{
    try {
        option = myscan.nextInt();
        inputOk = true;
    } catch (InputMismatchException  e) {
        System.out.println("Error, this is not an integer.");
        myscan.nextLine(); // to consume the \n that remains at the end of the line after using nextInt();
    }
}while (!inputOk);
这样它就会循环,直到你得到一个有效的数字

编辑

如果要再次打印菜单,则可以执行以下操作:在原始代码中,使用continue语句更改break语句,并包括对
nextLine
方法的调用:


您可以添加do while来读取捕获InputMismatchException的选项:

int option = 0;
boolean inputOk = false;
do{
    try {
        option = myscan.nextInt();
        inputOk = true;
    } catch (InputMismatchException  e) {
        System.out.println("Error, this is not an integer.");
        myscan.nextLine(); // to consume the \n that remains at the end of the line after using nextInt();
    }
}while (!inputOk);
这样它就会循环,直到你得到一个有效的数字

编辑

如果要再次打印菜单,则可以执行以下操作:在原始代码中,使用continue语句更改break语句,并包括对
nextLine
方法的调用:


不要在没有保证的情况下获取并期望整数,只需获取下一行的内容,并确定输入的值是否是一个带有如下正则表达式的整数

      while(running)
      {
          inputFromUser = myscan.nextLine();
          int option = -1; //some default invalid value
          boolean doSwitch = false;

          if(inputFromUser.matches("\\d+"))
          {
              option = Integer.parseInt(inputFromUser);
              doSwitch = true;
          }
          else{
              System.out.println("Incorrect input was received - " + inputFromUser);
          }

          if(doSwitch)
          {
              //switch logic
          }
      }

不要在没有保证的情况下获取并期望整数,只需获取下一行的内容,并确定输入的值是否是一个带有如下正则表达式的整数

      while(running)
      {
          inputFromUser = myscan.nextLine();
          int option = -1; //some default invalid value
          boolean doSwitch = false;

          if(inputFromUser.matches("\\d+"))
          {
              option = Integer.parseInt(inputFromUser);
              doSwitch = true;
          }
          else{
              System.out.println("Incorrect input was received - " + inputFromUser);
          }

          if(doSwitch)
          {
              //switch logic
          }
      }

我加了这个,但同样的事情还在发生。如果正确,它不会继续执行switch语句,如果不正确,它会崩溃尝试此建议后是否删除if语句?是的,只要正确,它就会工作,但在错误消息后不会返回到循环?能否至少添加整个while循环?确定。请参阅我的编辑。这是我添加的新版本的测试,但同样的事情仍然在发生。如果switch语句正确,它不会继续执行,如果它不是tDi,它将崩溃