繁体   English   中英

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

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

我知道java.util.Scanner有一个自动分隔符“”。 有什么办法可以摆脱在控制台的同一行中输入多个数字的人? 我希望它成为无效的输入。 例如,我希望一次只输入个位数。 我不希望有人在同一行输入“2 5”或“23”。 如果他们这样做,我不希望计算机处理每个数字。

为了达到您想要的结果,首先检查 String 是否为数字。 为此,请使用.matches("\\\\d")函数。 这将检查来自扫描仪输入是否为单个数字 然后,使用Integer.parseInt(String); 函数获取字符串,并将其转换为整数。 这样,您可以将 userInput 用作 Integer 而不是将其保留为 String。

这是代码:

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");
    }
    }
    
  }   
}

这是输出:

输出

暂无
暂无

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

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