user input check int only

后端 未结 4 520
抹茶落季
抹茶落季 2021-01-21 11:34

I am trying to have my user input not crash my program by restricting what the user can input such as:

  1. only being an int
  2. being between 1-30
<
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-21 12:05

    See dasblinkenlight's awnser with the NumberFormatException catch. I was thinking of doing that. This also works too:

    You need to combine the two loops like so:

    while(true) {
    if(!sc.hasNextInt) {
    System.out.println("Only Integers!");
    continue;
    }
    choose = sc.nextInt();
    if(choose <= 0) {
    System.out.println("The number you entered was too small.");
    continue;
    } else if(choose > 30) {
    System.out.println("The number you entered was too large.\nMax: 30");
    continue;
    }
    break;
    }
    sc.close();
    

提交回复
热议问题