+ 1

i don't know how to limit the iteration in my for loop code.

Someone please, help me with the syntax to print out " I love Java " for only 5 times. Thanks every body. https://code.sololearn.com/cKj4w2ObhPN9/?ref=app

13th Apr 2019, 1:59 AM
hviet75
hviet75 - avatar
6 Answers
+ 3
You should do: for(int x = 0, y = sc.nextInt(); x < y; x++){ // Rest of the code } EDIT: initially, x = 0 and y = the number you input. So if you input 5, you will see " I love Java" 5 times. I wish you success!
13th Apr 2019, 2:33 AM
Luis SepĂșlveda
Luis SepĂșlveda - avatar
+ 3
You can also write this: x = sc.nextInt(); x < 10; x++ But x <= x + 5 can not work because you increment x. for example input = 5 x = 5; x <= 10 (true); x++ x = 6; x <= 11 (true); x++ x = 7; x <= 12 ... and so on Hope this helps to understand why you get an infinite loop.
13th Apr 2019, 1:36 PM
Denise Roßberg
Denise Roßberg - avatar
+ 2
Oh, it's because there is an input, it causes confusion.. In this case, it is unnecessary. Here are variations: for(int x = 0; x < 5; x++) or for(int x = 0; x <= 4; x++) or for(int x = 5; x > 0; x--) And so forth. I wish you success!
13th Apr 2019, 2:37 PM
Luis SepĂșlveda
Luis SepĂșlveda - avatar
+ 2
If you only want to print something five times: for(int i = 0; i < 5; i++){ //print something } But I am not sure why you have a scanner in your code.
13th Apr 2019, 3:17 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
Thank you but I think your both codes not do exactly 5 times. I just want to print out 5 times no matter of whatever numbers people assign to "x" or "y" the result is always 5 times. ( Sorry if my English couldn't help you understand , because English is not my first language )
13th Apr 2019, 2:26 PM
hviet75
hviet75 - avatar
0
Denise Roßberg I just want to solve the math with whatever number people want to input for the value of "x" but the result is 5 sentences with " I Love Java " 😄
13th Apr 2019, 3:38 PM
hviet75
hviet75 - avatar