2014-11-06 156 views
0

我正在爲我的班級做作業。我寫了一個方法來引發一個錯誤,如果輸入了一個不正確的整數,我試圖給出一個錯誤消息,當一個字符串被輸入,而不是一個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"); 
} 
+0

如果你使用nextInt,你不能得到一個'String'。 – Jens 2014-11-06 06:31:59

+0

代碼片段[不適用於發佈示例代碼塊](http://meta.stackoverflow.com/questions/271647/stack-snippets-being-misused)。改爲使用**代碼示例{} **按鈕。 – Radiodef 2014-11-06 07:01:10

回答

1

使用下面的代碼。所以當你下一次嘗試輸入String時,它會拋出InputMismatchException異常,你可以捕獲異常並說你讓用戶知道用戶輸入了無效輸入並讓他重試。

+0

這對我有用!非常感謝你。 – Jakob 2014-11-06 06:47:57

+0

非常歡迎。 – SMA 2014-11-06 06:52:42

0

那麼,你可以使用next()獲得價值爲String,然後解析值,看看是否StringInteger被輸入。

String str = stdin.next(); 
for (char c:str.toCharArray()) { 
    if (!Character.isDigit(c)) { 
     throw new IllegalArgumentException("Invalid character entered: " + c); 
    } 
} 
0

檢查java文件的nextInt() - 是stdin掃描儀?如果是這樣,如果輸入一些非整數文本,則nextint()將引發異常。你可能想要捕捉並打印自己的錯誤。儘管如此,你甚至可能比任務所期望的更進一步。短語「如果輸入了錯誤的整數會引發錯誤」可能意味着只會輸入整數。這取決於教練/班級。

0
import java.util.*; 
public class Test 
{ 
    public static void main(String args[]) 
    { 
     Scanner in = new Scanner(System.in); 
     try 
     { 
      int i = in.nextInt(); 
     } 
     catch(InputMismatchException e) 
     { 
      e.printStackTrace(); 
     } 

    } 
} 

我希望這會以服務器爲例。當你給一個字符或字符串。引發異常。

相關問題