//File name: SmallIO.java
import java.util.Scanner;
public class SmallIO{
public static void main(String[] args){
Scanner keyboard = new Scanner (System.in);
String a = ""; // initialise to empty string
while (true){
//an infinite loop, use Ctrl-C (from command prompt) to quit
System.out.println("Enter a line:");
a = keyboard.nextLine();
System.out.println("Your line: " + a);
System.out.println();
}//end of while
}//end of main
}//end of class
Asked
Active
Viewed 1,049 times
-6

Federico klez Culloca
- 26,308
- 17
- 56
- 95

huehuehue
- 1
- 1
-
If you need to count use a `for` loop, not a `while`. – Federico klez Culloca Sep 07 '20 at 14:49
-
Also, you may want to break the loop on some other condition, I guess. Because as it stands you're repeatedly asking for a value and ignoring what is input. – Federico klez Culloca Sep 07 '20 at 14:50
2 Answers
3
There are multiple ways, the simplest one would be to use an actual for loop:
for (int i = 1; i <=5; i++) {....}
This is the same as:
int i = 1;
while (i <= 5) {.... i++; }

AndreiXwe
- 723
- 4
- 19
1
To break a loop(any loop), you use the break
statement.
To break a loop after 5 iterations, you use a counter
This is one of the way to use a counter in combination with break
int counter = 0;
while(true) {
counter++;
if (counter == 5) break;
}

dee cue
- 983
- 1
- 7
- 23