How to insist that a users input is an int?

前端 未结 7 1974
日久生厌
日久生厌 2020-12-10 10:09

Basic problem here.. I will start off by asking that you please not respond with any code, as that likely will only confuse me further (programming noob). I am looking for

相关标签:
7条回答
  • 2020-12-10 10:46

    Here's a simple example with prompts and comments.

    Scanner scan = new Scanner(System.in);
    System.out.print("Enter an integer: "); // Initial prompt for input
    
    // Repeat until next item is an integer
    while (!scan.hasNextInt()) 
    {        
        scan.next(); // Read and discard offending non-int input
        System.out.print("Please enter an integer: "); // Re-prompt
    }
    
    // At this point in the code, the user has entered an integer
    int input = scan.nextInt(); // Get the integer
    
    // And now you can use the input variable.
    
    0 讨论(0)
提交回复
热议问题