简体   繁体   中英

How to take only a single input from java.util.Scanner?

I know that java.util.Scanner has an automatic delimiter " ". Is there any way I could get rid of someone entering more than one number in the same line of the console? I want it to become an invalid input. For example, I only desire single digits to be inputted at a time. I don't want someone to put in "2 5" or "23" on the same line. If they do, I don't want the computer to process each number.

In order to achieve your desired results, first check if the String is a number. To do this, use the .matches("\\\\d") function. This checks if the Input from the Scanner is a single number . Then, use the Integer.parseInt(String); function to take the string, and turn it into an integer. This way, you can use the userInput as an Integer instead of leaving it as a String.

Here is the code:

import java.util.Scanner; 

public class test {
  public static void main(String args[]) {
    while (true){
    System.out.println("Type a single number in!\n");
    Scanner userInt = new Scanner(System.in);
    String userInp = userInt.nextLine();
    if (userInp.matches("\\d")){// Checks if userInp is a single digit
      System.out.println("\nYou are correct!\n");
      int userNumber = Integer.parseInt(userInp); // Turns the userInp(String) into the userNumber (Integer)
      System.out.println("Your number was " + userNumber + "!\n");// Prints out the number(which is now an Integer instead of a String)
    } else if (userInp.equals("-break")) {
      break;
    } else {
      System.out.println("\nYou are incorrect.\n");
      System.out.println("We couldn't read your number because it wasn't a single digit!\n");
    }
    }
    
  }   
}

Here is the output:

输出

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM