-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
  • 263,859
  • 56
  • 671
  • 702
VeeraLavan
  • 21
  • 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,644
  • 2
  • 18
  • 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,398
  • 3
  • 16
  • 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,130
  • 7
  • 38
  • 78