我正在爲我的班級做作業。我寫了一個方法來引發一個錯誤,如果輸入了一個不正確的整數,我試圖給出一個錯誤消息,當一個字符串被輸入,而不是一個int,但我不知道如何。我不允許使用parsInt或內置的字符串方法。我會很感激任何幫助。當輸入字符串而不是int時拋出錯誤
int playerNum = stdin.nextInt();
while (invalidInteger(playerNum) == -1 || invalidInteger(playerNum) == -2 || invalidInteger(playerNum) == -3)
{
if(invalidInteger(playerNum) == -1)
{
System.out.println("Invalid guess. Must be a positive integer.");
System.out.println("Type your guess, must be a 4-digit number consisting of distinct digits.");
count++;
}
if(invalidInteger(playerNum) == -2)
{
System.out.println("Invalid guess. Must be a four digit integer.");
System.out.println("Type your guess, must be a four digit number consisting of distinct digits.");
count++;
}
if(invalidInteger(playerNum) == -3)
{
System.out.println("Invalid guess. Must have distinct digits.");
System.out.println("Type your guess, must be a four digit number consisting of distinct digits.");
count++;
}
playerNum = stdin.nextInt();
}
增加了這個片段來捕捉異常。感謝almas shaikh。當你輸入字符串,而不是整數的
try {
int playerNum = scanner.nextInt();
//futher code
} catch (InputMismatchException nfe) {
System.out.println("You have entered a non numeric field value");
}
掃描器拋出InputMismatchException時:
try {
int playerNum = scanner.nextInt();
//futher code
} catch (InputMismatchException nfe) {
System.out.println("You have entered a non numeric field value");
}
如果你使用nextInt,你不能得到一個'String'。 – Jens 2014-11-06 06:31:59
代碼片段[不適用於發佈示例代碼塊](http://meta.stackoverflow.com/questions/271647/stack-snippets-being-misused)。改爲使用**代碼示例{} **按鈕。 – Radiodef 2014-11-06 07:01:10