2012-10-11 42 views
2

我只是在玩Java.I'm试图强制我的程序只接受3位数字。 我相信我已经使用while循环成功地完成了这个操作(如果我错了,请纠正我)。 但是如果用户输入一个字符串,我该如何去打印一个错误语句。例如:“abc”。如果用户输入字符串而不是Int,可能会出现异常

我的代码:

import java.util.Scanner; 
    public class DigitSum { 

    public static void main(String[] args) { 

    Scanner newScan = new Scanner(System.in); 

     System.out.println("Enter a 3 digit number: "); 
     int digit = newScan.nextInt(); 

     while(digit > 1000 || digit < 100) 
      {   
      System.out.println("Error! Please enter a 3 digit number: "); 
      digit = newScan.nextInt(); 
      } 

     System.out.println(digit); 
     } 
    } 

回答

1

这个怎么样?

public class Sample { 
    public static void main (String[] args) { 
     Scanner newScan = new Scanner (System.in); 

     System.out.println ("Enter a 3 digit number: "); 
     String line = newScan.nextLine(); 
     int digit; 
     while (true) { 
      if (line.length() == 3) { 
       try { 
        digit = Integer.parseInt (line); 
        break; 
       } 
       catch (NumberFormatException e) { 
        // do nothing. 
       } 
      } 

      System.out.println ("Error!(" + line + ") Please enter a 3 digit number: "); 
      line = newScan.nextLine(); 
     } 

     System.out.println (digit); 
    } 
} 

正则表达式版本:

public class Sample { 
    public static void main (String[] args) { 
     Scanner newScan = new Scanner (System.in); 

     System.out.println ("Enter a 3 digit number: "); 
     String line = newScan.nextLine(); 
     int digit; 

     while (true) { 
      if (Pattern.matches ("\\d{3}+", line)) { 
       digit = Integer.parseInt (line); 
       break; 
      } 

      System.out.println ("Error!(" + line + ") Please enter a 3 digit number: "); 
      line = newScan.nextLine(); 
     } 

     System.out.println (digit); 
    } 
} 
+0

这是完美的。非常感谢。它正是我想要实现的。感谢所有人。你所有的答案都是有效的。这个对我来说效果更好:D – binary101

+0

“Integer.parseInt()”不是本质的。 您可以使用regexp而不是“Integer.parseInt()”。 – Ruzia

+0

看看你的答案Ruzia,你使用了'Integer.parseInt()'我认为这是非常本质的(不管那是什么意思)。另外,为什么你考虑到你拿了它而降低了我的答案? – JonH

2

嵌入用于读取try catch块中的int会产生每当进入输入错误则显示你在catch块想要的任何消息的异常代码

0

您可以检查一个字符串是否是数字值在以下几个方面:

1)使用try/catch块

try 
{ 
    double d = Double.parseDouble(str); 
}catch(NumberFormatException nfe) { 
    System.out.println("error"); 
} 

2)使用正则表达式

if (!str.matches("-?\\d+(\\.\\d+)?")){ 
    System.out.println("error"); 
} 

3)使用NumberFormat类

NumberFormat formatter = NumberFormat.getInstance(); 
ParsePosition pos = new ParsePosition(0); 
formatter.parse(str, pos); 
if(str.length() != pos.getIndex()){ 
    System.out.println("error"); 
} 

4)使用Char.isDigit()

for (char c : str.toCharArray()) 
{ 
    if (!Character.isDigit(c)){ 
     System.out.println("error"); 
    } 
} 

你可以看到How to check if a String is numeric in Java更多信息

2

这里nextInt方法本身抛出一个InputMismatchException如果输入错误。

try { 
    digit = newScan.nextInt() 
} catch (InputMismatchException e) { 
    e.printStackTrace(); 
    System.err.println("Entered value is not an integer"); 
} 

这应该做。

+0

这很好。将工作良好。谢谢。 – binary101

0

如何我它是使用if语句会做。 if语句应该是这样的:

if(input.hasNextInt()){ 
    // code that you want executed if the input is an integer goes in here  
} else { 
    System.out.println ("Error message goes here. Here you can tell them that you want them to enter an integer and not a string."); 
} 

注意:如果你想让他们进入一个字符串,而不是整数,更改条件的 if语句input.hasNextLine()而非input.hasNextInt()

第二个注意:input就是我给我的扫描仪命名的。如果您命名您的煎饼,那么您应该输入pancakes.hasNextInt()pancakes.hasNextLine()

希望我帮助和祝你好运!

0

你想要一个异常如果用户输入一个字符串,如“ABC”,而不是一个整数值,则InputMismatchException是适合你的出现。

让我给你一个基本的例子。

public static void main(String[] args) 
    { 
     Scanner ip = new Scanner(System.in); 
     int a; 
     System.out.println("Enter Some Input"); 
     try{ 
      a = ip.nextInt(); 
     } 
     catch(InputMismatchException msg){ 
      System.out.println("Input Mismatch Exception has occured " + msg.getMessage()); 
     } 
    } 
相关问题