import java.util.Scanner;
class BreakWhileLoop {
public static void main(String[] args) {
int n;
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Input an integer");
n = input.nextInt();
if (n == 0) {
break;
}
System.out.println("You entered " + n);
}
}
}
Code Breakdown:
1. Importing Scanner Class:
import java.util.Scanner;
This imports the Scanner class, which is part of the Java standard library and is used to take input from the user.
2. Class Definition:
class BreakWhileLoop
This defines a class named BreakWhileLoop.
3. Main Method:
public static void main(String[] args)
This is the entry point of the Java program. The execution of the program begins with this method.
4. Variable Declaration:
int n;
A variable n of type int is declared to hold the integer entered by the user.
5. Creating Scanner Object:
Scanner input = new Scanner(System.in);
This makes a Scanner object called input, which will be used to read the user’s input from the console.
6. While Loop:
while (true)
This is an infinite while loop which will continue executing if the given condition true holds good. As it is known that the condition true is always true, hence this loop will keep running till it is stopped using a break statement in a program manually.
7. Asking the User to Provide Input:
System.out.println(“Input an integer”);
This statement asks for an integer from the user.
8. Reading User Input:
n = input.nextInt();
This line reads the integer input from the user and stores the value in the variable n.
9. Condition Check and Break:
if (n == 0)
{
break;
}
This checks if the input integer n is equal to 0. If it is, the break statement executes which terminates the loop from further iteration.
10. Print the Input:
System.out.println(“You entered ” + n);
If n is not 0, this line prints the message “You entered” followed by the value of n.
11. End of Program:
Once the loop is broken (when n is 0), the program ends.
Example Walkthrough:
- The program begins by asking the user to input an integer.
- If the user inputs a non-zero integer, it will print “You entered [n]” and prompt for another integer.
- If the user inputs 0, the loop will terminate, and the program will stop.
Output Example
Case 1:
Input an integer
5
You entered 5
Input an integer
10
You entered 10
Input an integer
0
Explanation of Output:
1. The user inputs 5, which is printed as “You entered 5”.
2. Then the user types 10 that prints out as “You entered 10”
3. Lastly, he inputs 0. Then the programme halts in case of that the break statement appears.
This is the programme which keeps inputting numbers and displays them back till it reach number 0.