2014-11-06 157 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(); 
     } 

    } 
} 

我希望这会以服务器为例。当你给一个字符或字符串。引发异常。

相关问题