2013-09-23 30 views
0

該程序告訴用戶輸入的整數是否爲零,正和偶數或奇數,或負數,偶數或奇數。如果輸入非整數時如何打印錯誤?

我的問題是如果輸入非整數,我想在println中添加一個錯誤。看最後一行。

import java.util.Scanner; 

public class IntegerCheck { 
    public static void main(String [] args) { 

    int x; 
    System.out.println("Enter an integer value:"); 

    Scanner in = new Scanner(System.in); 
    x = in.nextInt(); 
    //String x = in.nextInt(); 

    if (((x % 2) == 0) && (x< 0)) 
    System.out.println(x + " is a negative, even integer."); 
    else if (((x % 2) == 0) && (x == 0)) 
    System.out.println(x + " is Zero."); 
    else if ((x % 2)==0) 
    System.out.println(x + " is a positive, even integer."); 

    if (((x % 2) != 0) && (x<0)) 
    System.out.println(x + " is a negative, odd integer."); 
    else if ((x % 2) != 0) 
    System.out.println(x + " is a positive, odd integer."); 

    if (x != 'number') 
    System.out.println(x + " is not an integer."); 


} 
} 

回答

5

您可以使用Scanner.nextInt()拋出的InputMismatchException。將代碼環繞在try/catch區塊中並捕獲InputMismatchException。它看起來像 -

try{ 
x = in.nextInt(); 

if (((x % 2) == 0) && (x< 0)) 
    System.out.println(x + " is a negative, even integer."); 
    else if (((x % 2) == 0) && (x == 0)) 
    System.out.println(x + " is Zero."); 
    else if ((x % 2)==0) 
    System.out.println(x + " is a positive, even integer."); 

    if (((x % 2) != 0) && (x<0)) 
    System.out.println(x + " is a negative, odd integer."); 
    else if ((x % 2) != 0) 
    System.out.println(x + " is a positive, odd integer."); 
} 
catch(InputMismatchException e){ 
    System.out.println("You did not enter an integer!"); 
}