如何打印错误消息

时间:2014-03-05 06:19:48

标签: java

当整数无效时,如何从函数中打印错误消息? 如果我输入字符串或字符, 只显示“TYPE NUMBER”

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");
        }
    }

}

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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
        }
    }

}

答案 2 :(得分: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
}