[英]conditional statement if user enters integer instead of String
嘿伙計們,我的實驗室練習需要幫助。 我只需要通過這個問題..我唯一的問題是我需要確保如果用戶嘗試在字符串中輸入一個數字(特別是 int)會出現異常“但是**我正在使用java.util.Scanner
並將輸入作為String
讀取
else if (userInput.hasNextInt())
只是我的問題
import java.util.*;
public class Quizbee{
public static void main (String args[]){
Scanner sc = new Scanner(System.in);
int score = 0;
String userInput;
String answerKey[] = {"A", "C", "B", "B", "C"}; //A, C,
String multichoice[][] = {{"A = Leonardo Da Vinci ", "B = Albert Einstein ","C = Stephen Hawking"}, //[0][0],[0][1],[0][2]
{"A = 9 ", "B = 8 ", "C = 7 "}, //[1][0],[1][1],[1][2]
{"A = Rodrigo Duterte ", "B = Ferdinand Marcos ", "C = Ninoy Aquino "}, //[2][0],[2][1],[2][2]
{"A = John F. Kennedy ","B = Abraham Lincoln ","C = Ronald Reagan "}, //[3][0],[3][1],[3][2]
{"A = Floyd Mayweather ","B = Manny Pacquaio ", "C = Muhammad Ali "}}; //[4][0],[4][1],[4][2]
{}
String arrQuestion[] = {"The Renaissance Man?", "prime number?","Longest-term serving Pres. of PH",
"1st US President to be assassinated", "Nicknamed \"The Greatest\" in the boxing history"};
for (int x = 0; x<arrQuestion.length; x++)
{
try
{
System.out.println("\n" + (x+1)+". " + arrQuestion[x]);
System.out.print(multichoice[x][0] + multichoice[x][1] + multichoice[x][2]+": ");
userInput = sc.nextLine();
if(userInput.equalsIgnoreCase(answerKey[x]))
{
System.out.println("Correct!");
score = score + 1;
}
else if(!userInput.equalsIgnoreCase(answerKey[x]))
{
if(userInput.isEmpty())
{
throw new NullPointerException();
}
else if(!userInput.equalsIgnoreCase("A") && !userInput.equalsIgnoreCase("B") && !userInput.equalsIgnoreCase("C"))
{
throw new OutOfRangeMisception();
}
else if(userInput.hasNextInt())
{
throw new InputMismatchException();
}
else
{
System.out.println("Wrong!");
score = score + 0;
}
}
}
catch(OutOfRangeMisception oor)
{
System.out.println(oor.getMessage());
}
catch(NullPointerException ex)
{
System.out.println("No answer. please try again.");
}
catch(InputMismatchException ex)
{
System.out.println("Wrong data type.");
}
}
System.out.println("\nYour score: " + score);
}
}
您可以使用Integer.parseInt(userInput)
。 如果成功,則用戶輸入了一個整數,否則會出現異常。 所以如果它是一個整數,你可以拋出你的異常,否則你會捕獲NumberFormatException
。
您可以使用這個簡單的方法來測試String
是否為數字
public boolean isNumber(String text) {
try {
Integer.parseInt(text);
return true;
} catch (NumberFormatException exception) {
return false;
}
}
如果您只使用 Java,請使用StringUtils.isNumeric()
:
檢查字符串是否僅包含 unicode 數字或空格 (' ')。 小數點不是 Unicode 數字並返回 false。
null 將返回 false。 空字符串 (length()=0) 將返回 true。
所以在你的情況下,你會使用:
else if(StringUtils.isNumeric(userInput))
請注意,這不適用於 Android。 相反,您需要TextUtils.isDigitsOnly()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.