catching the exception is one way:
import java.util.InputMismatchException;
import java.util.Scanner;
public class positive {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num;
System.out.println("Enter number");
try {
num = input.nextInt();
if (num < 0) {
System.out.println("This is a negative number");
}
else if (num == 0) {
System.out.println("Zero");
}
else if (num > 0) {
System.out.println("This is a positive number");
}
}
catch(InputMismatchException ime)
{
System.out.println("Error: Invalid number");
}
}
}
But it's not really the "best" way... best of course being subjective. Generally, if you can do something without raising and catching exceptions, you should. in this case, it's the hasNextInt() function.
import java.util.InputMismatchException;
import java.util.Scanner;
public class positive {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num;
System.out.println("Enter number");
if(input.hasNextInt())
{
num = input.nextInt();
if (num < 0) {
System.out.println("This is a negative number");
}
else if (num == 0) {
System.out.println("Zero");
}
else if (num > 0) {
System.out.println("This is a positive number");
}
}
else{
System.out.println("Invalid number");
}
}
}
and here's my pointlessly reduced version.
import java.util.Scanner;
public class positive {
public static int Sign(int argument)
{
return argument<0?-1:argument==0?0:1;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num;
String[] resultmessages = new String[]
{"This is a negative number", "Zero","This is a positive number"};
System.out.println("Enter number");
if(input.hasNextInt())
{
num = input.nextInt();
System.out.println(resultmessages[Sign(num)+1]);
}
else
System.out.println("Error: Invalid number");
}
}