简体   繁体   English

如何只从 java.util.Scanner 获取一个输入?

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

I know that java.util.Scanner has an automatic delimiter " ".我知道java.util.Scanner有一个自动分隔符“”。 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.我不希望有人在同一行输入“2 5”或“23”。 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.为了达到您想要的结果,首先检查 String 是否为数字。 To do this, use the .matches("\\\\d") function.为此,请使用.matches("\\\\d")函数。 This checks if the Input from the Scanner is a single number .这将检查来自扫描仪输入是否为单个数字 Then, use the Integer.parseInt(String);然后,使用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.这样,您可以将 userInput 用作 Integer 而不是将其保留为 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:这是输出:

输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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