2014-03-05 87 views
-1

如何在整數無效時從我的函數打印錯誤消息? 如果我輸入字符串或字符, 顯示 「TYPE號僅」如何打印錯誤消息

import java.util.*; 

public class CheckNumberOnly { 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     int a,i; 
     Scanner obj=new Scanner(System.in); 
     System.out.println("TYPE A"); 
     a=obj.nextInt(); 
     i=a; 
     if(i==a){ 
      System.out.println("A is "+i); 
     } 
     else{ 
      System.out.println("TYPE NUMBER ONLY"); 
     } 
    } 

} 
+4

您使用了'nextInt()'。它不能返回一個無效的整數。 –

+0

如果你想打印錯誤信息,你可以使用'System.err'而不是'System.out'。但@SotiriosDelimanolis是正確的。 – Tinfoilboy

回答

0

使用try/catch塊,像這樣來測試一個整數

Scanner sc=new Scanner(System.in); 
try 
{ 
    System.out.println("Please input an integer"); 
    //nextInt will throw InputMismatchException 
    //if the next token does not match the Integer 
    //regular expression, or is out of range 
    int usrInput=sc.nextInt(); 
} 
catch(InputMismatchException exception) 
{ 
    //Print "This is not an integer" 
    //when user put other than integer 
    System.out.println("This is not an integer"); 
} 

Source

0
import java.util.*; 

public class CheckNumberOnly { 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     int a; 
     Scanner obj=new Scanner(System.in); 
     try{ 
     a=obj.nextInt(); 
     System.out.println("A is "+a); 
     } 
     catch(InputMismatchException e){ 
      System.out.println("TYPE NUMBER ONLY"); 
      e.printStackTrace();///you can use this method to print your exception 
     } 
    } 

} 
0

使用Try/Catch塊,像這樣測試一個整數

Scanner obj=new Scanner(System.in); 
try{ 
    int usrInput = obj.nextInt(); 
    System.out.println("A is "+usrInput); 
} catch(InputMismatchException e){ 
    System.out.println("TYPE NUMBER ONLY"); 
    e.printStackTrace();///you can use this method to print your exception 
}