I am having trouble creating the code to end the program if the user enters -99. I have everything else done. The int "testNum" is what holds the value for -99. Can someone point me in the right direction on how to make it where when the user enters -99 then the program stops? Here is my code

import java.util.Scanner;

public class LargeSmall
{
	public static void main(String[] args)
	{
		int numbers;
		int smallest = 0;
		int largest = 0;
		int count = 0;
		int val;
		int testNum = -99;
		int max;
		
		Scanner keyboard = new Scanner(System.in);
		
		
		System.out.println("How many numbers will you enter?");
		max = keyboard.nextInt();
		

		

		
			for (count = 0; count < max; count++)
			{		
			
				System.out.println("Enter number ");
				val = keyboard.nextInt(); 			
		
				if (val > largest)
				{
				 largest = val;
				}
			
				if (val < smallest) 
				{
				smallest = val;
				}
			}
		
		

System.out.println(smallest);
System.out.println(largest);

}
}

The command System.exit(0); will kill your program. So if you have the lines:

if (val == testNum)
    System.exit(0);

Then your code will exit if the testNum is entered. Note that this is not like breaking from the loop -- your program will basically jump to the end of the main method with this command.

So thats pretty much like break; , but it skips the program?

On a side note -- using the keywords break and continue is considered by many to be messy coding and the mark of an amateur programmer ^^ so try to avoid them:

Code with break:

Scanner input = new Scanner(System.in);
int x;
while (true)
{
    x = input.nextInt();
    if (x == 5)
        break;
}

Same code without break:

Scanner input = new Scanner(System.in);
int x;
boolean exit = false;
while (!exit)
{
    x = input.nextInt();
    if (x == 5)
        exit = true;
}

Just a stylistic point :P

Thanks kvass, that is very helpful because my professor takes -5 points for exiting a loop using the break command.

This article has been dead for over six months. Start a new discussion instead.