-6
//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
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
huehuehue
  • 1
  • 1

2 Answers2

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