[英]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.