0
Braking a while loop??
Can anyone explain why the 1st while loop isnt breaking if my input is over 5 or below 0?.. although theres a break it still jumps over to the next while. I do understand theres switch statments im just experimenting with loops.^-^ thanks Scanner x = new Scanner(System.in); int z = 5; int y = x.nextInt(); while(y > 5|| y < 0){System.out.println("Enter a number between 1 - 5 to loop 5x");break;} while(z > 0){System.out.println(y);--z;}
13 Answers
+ 1
@ chaotic i did it!!
Scanner x = new Scanner(System.in);
int z = 5;
int y = x.nextInt();
while(y > 5|| y < 0){System.out.println("Enter a number between 1 - 5 to loop 5x");System.exit(0);}
while(z > 0){System.out.println(y);--z;}
+ 5
If either condition is true the while loop continues you want &&
+ 2
It's working correctly for me. The way it is written now, it will only enter the first while loop if the number entered is 6 or greater, or -1 or less. If the number entered is 0, 1, 2, 3, 4, or 5 the while loop is entered and the System.out.println is only ran once, meaning that the break statement is exiting the loop as it should. Then the next while loop outputs the number entered 5 times. If the number entered is outside the range 0-5 then the System.out.println will not be output and only the second while loop is ran outputting the number entered 5 times.
+ 1
thanks jay but it still continues to loop :/ i would use if statement but system wont allow the brake inside.
+ 1
The way the code is written that is exactly what it should do as I explained above.
+ 1
oh i understand my aim is to stop the loop of a number higher then 5 or lower the 0? i just thought the break would prevent it going to the next line??
+ 1
Remember, the break statement is only in the first while loop. The second while loop will always output the number entered exactly 5 times.
+ 1
You can, but you'd need a break statement for each while loop and if statements are usually used for determining the conditions for when you want to break from the while loop. If you are just placing a break in a loop that is always ran (like in your first while loop), then you have no need for the loop in the first place.
+ 1
Lol, I guess that's one way to do it.
0
@ chaoticDawg, but if i put say 33 it will loop 5 times? is this not happening with you?
0
is there away to stop it? i only want to loop between 0 & 5 anything higher or lower i want it to terminate before the next while thanks
0
Scanner x = new Scanner(System.in);
int z = 5;
System.out.print("Enter a number between 0 - 5 to loop 5x ");
int y = x.nextInt();
if(y > -1 && y < 6) {
System.out.println();
while(z > 0) {
System.out.println(y);
--z;
}
}
This should only output the entered number z times if it is in the range 0-5.
0
@ chaoticDawg im guessing you cant brake out of 2 while loops? without using an if()? sorry to do this lol ^_^