-1

How can I print error messages from my function when the integer are invalid? If I type string or character, Show "TYPE NUMBER ONLY"

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

}
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
VeeraLavan
  • 46
  • 7

3 Answers3

0

Use Try/Catch block, something like this to test an integer

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

Community
  • 1
  • 1
Kamlesh Arya
  • 4,864
  • 3
  • 21
  • 28
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
        }
    }

}
Engineer
  • 1,436
  • 3
  • 18
  • 33
0

Use Try/Catch block, something like this to test an integer

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
}
hatellla
  • 4,796
  • 8
  • 49
  • 101