I want to terminate my while loop when user press 2 for exit but I entered loop again if user press 2 it did not exit please help me about it thanks
int count = 1;
while(count <=3) {
System.out.println(" Enter any option");
System.out.println(" Enter 1 for addition");
System.out.println(" Enter 2 for exit");
Scanner input = new Scanner (System.in);
int option = input.nextInt();
if(option==2) {
System.out.println("Thank you for using app");
}
else
switch(option) {
case 1 :
System.out.println("welcome to addtion");
int sum;
System.out.println("Enter first number");
int x = input.nextInt();
System.out.println("Enter second number");
int y = input.nextInt();
sum=x+y;
System.out.println(sum);
break;
case 2 :
System.out.println("do you want to exit ? ");
break;
}
}
Perhaps your loop's condition should be :
while (option != 2)
Your current condition - while (count <=3)
doesn't make much sense, since count
is not updated inside the loop.
You could use a labeled break
input: while( count <=3) {
...
...
switch( option) {
...
case 2:
...
break input; // break the outer while loop
...
But I think it's generally better to encapsulate the while loop in a method and 'return' in cases like that.
Your while loop condition is suspect but a one line change would suffice.
if(option==2) {
System.out.println("Thank you for using app");
break;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.