2012-10-11 46 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()); 
     } 
    } 
相關問題