user input check int only

后端 未结 4 476
抹茶落季
抹茶落季 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:03
    do:
    get number from user
    if non integer format is entered{
    number = -1;}
    while: 1 < number < 30
    
    0 讨论(0)
  • 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();
    
    0 讨论(0)
  • 2021-01-21 12:12

    You need to combine the two loops, so that both checks happen every time the end-user enters something new:

    for(;;) {
        if(!sc.hasNextInt() ) { 
            System.out.println("only integers!: "); 
            sc.next(); // discard
            continue;
        } 
        choose=sc.nextInt();
        if( choose<=0 || choose>30)
        {
            System.out.print("no, 1-30: ");
            continue;
        }
        break;
    }
    

    After the loop exits, choose is a number between 1 and 30, inclusive.

    0 讨论(0)
  • 2021-01-21 12:17
        String choose = "";
        System.out.println("Test if input is an integer. Type 'quit' to exit.");
        System.out.print("Type an integer: ");
        Scanner sc=new Scanner(System.in);
    
        choose = sc.nextLine();
    
        while (!(choose.equalsIgnoreCase("quit"))) {
            int d = 0;
            try {
                d = Integer.parseInt(choose);
    
                if (!(d > 0 && d < 31)) {
                    System.out.println("Being between 1-30");
                } else {
                    System.out.println("Input is an integer.");
                }
            } catch (NumberFormatException nfe) {
                System.out.println("Enter only int");
            }
    
            System.out.print("Type an integer to test again or 'quit' to exit: ");
            sc = new Scanner(System.in);
            choose = sc.nextLine();
        }
    
        sc.close();
        System.out.print("Program ends.");
    
    0 讨论(0)
提交回复
热议问题