if / else Statement

The next statement will provide us a way to branch our program based on some condition.  The if / else statement has the following form:

if (condition)
{
    ...
}
else
{
   ...
}

If the condition is true then the code enclosed in the first curly brackets will be executed and if the condition is false then the code enclosed in the second curly brackets will be executed.

Let’s see how this works in practice. Suppose we want to write a program that asks the user to enter an number and then prints out whether it is positive or negative. Since we will be asking for a number, this will be similar to the program we wrote earlier where we asked for the user’s age.

	public static void main(String[] args) 
	{
		Scanner input = new Scanner(System.in);
		int number;
		
		System.out.println("Enter a number");
		number = input.nextInt();
		
		if (number < 0)
		{
			System.out.println("The number is negative");
		}
		else
		{
			System.out.println("The number is zero or positive");
		}
		
		input.close();
	}

We first read a number from the console, and then print one thing if it is less than zero and another if it is not less than zero.  Try this out.

Note that each time you enter a number, the program will stop since it reaches the end of the main function.  To test it with a different number, you need to start the program again.

Let’s combine what we learned about loops so that our will repeatedly ask for a number, up to 10 times, and print the result.  Take a crack at changing the program yourself before you look at my solution.

.

.

.

.

	public static void main(String[] args) 
	{
		Scanner input = new Scanner(System.in);
		int count;
		int number;
		
		for (count = 1 ; count <= 10 ; count++)
		{
			System.out.println("Enter a number");
			number = input.nextInt();
			
			if (number < 0)
			{
				System.out.println("The number is negative");
			}
			else
			{
				System.out.println("The number is zero or positive");
			}
		}
		
		input.close();
	}

Before we move on, what do you think will happen if, when asked to enter a number, you enter the string ‘abc’ instead? Why don’t you try it and see? What you should see is something like:

Enter a number
abc
Exception in thread "main" java.util.InputMismatchException
	at java.util.Scanner.throwFor(Unknown Source)
	at java.util.Scanner.next(Unknown Source)
	at java.util.Scanner.nextInt(Unknown Source)
	at java.util.Scanner.nextInt(Unknown Source)
	at HelloWorld.main(HelloWorld.java:15)

What has happened? What you are seeing is an error (called an exception) that Java has encountered. The nextInt function is expecting to see an integer, and instead it sees a text string. It doesn’t know what to do so it raises an exception.  When this happens, if there is not some code to handle the exception, then your program will terminate and when it does, it prints out some debugging information to help you determine where the error occured.

What you are seeing is called a stack trace and shows you all of the calls that were made before the exception occurs.  Here we can see that on line 15 of our HellowWorld.main function, we call nextInt which then calls some other internal functions until finally the exception is thrown. We can see that the problem is with line 15 of our source code which is, of course, the following line:

			number = input.nextInt();

And the problem is InputMismatchException which means that the function is expecting to see different input than it is currently presented with.

We would, of course, like to handle this exception more gracefully.  Rather than terminating our program, we would like to simply ignore the line and ask the user to enter the number again. There are several ways of handling this. The one we are going to use here is to check to make sure that a number is present before we call the nextInt function.

If we look at the documentation for the Scanner class, we will find that it has a function hasNextInt() which can be used to determine if the next input from the console contains an integer or not. Using this function, we can change our code as follows:

	public static void main(String[] args) 
	{
		Scanner input = new Scanner(System.in);
		int count;
		int number;
		
		for (count = 1 ; count <= 10 ; count++)
		{
			System.out.println("Enter a number");
			
			if (input.hasNextInt())
			{
				number = input.nextInt();
				
				if (number < 0)
				{
					System.out.println("The number is negative");
				}
				else
				{
					System.out.println("The number is zero or positive");
				}
			}
			else
			{
				System.out.println("You did not enter a number, please reenter");
			}
		}
		
		input.close();
	}

Now run your program and enter ‘abc’ instead of a number.  You should see the following output:

Enter a number
abc
You did not enter a number, please reenter
Enter a number
You did not enter a number, please reenter
Enter a number
You did not enter a number, please reenter
Enter a number
You did not enter a number, please reenter
Enter a number
You did not enter a number, please reenter
Enter a number
You did not enter a number, please reenter
Enter a number
You did not enter a number, please reenter
Enter a number
You did not enter a number, please reenter
Enter a number
You did not enter a number, please reenter
Enter a number
You did not enter a number, please reenter

What is going wrong?  Why didn’t it let us enter a new number.  The problem is that the check for hasNextInt check to see if the next input is an integer, but if it is not, it does not remove what is currently there. So once we have entered a non-number, it will always be a non-number and the loop will simply continue fore the 10 iterations that we have specified.

What we need to do is that if the user enters something other than a number, we need to read the rest of the line so the user can enter a new number. We can do this as follows:

	public static void main(String[] args) 
	{
		Scanner input = new Scanner(System.in);
		int count;
		int number;
		
		for (count = 1 ; count <= 10 ; count++)
		{
			System.out.println("Enter a number");
			
			if (input.hasNextInt())
			{
				number = input.nextInt();
				
				if (number < 0)
				{
					System.out.println("The number is negative");
				}
				else
				{
					System.out.println("The number is zero or positive");
				}
			}
			else
			{
				System.out.println("You did not enter a number, please reenter");
			}
			
			input.nextLine();	// Read the remainder of the line
		}
		
		input.close();
	}

We added the call to nextLine to flush the remainder of each line each time through the loop.  This will also deal with the case where the user enters extra stuff after the number. Try it out.

Next: Switch Statement