Input Loop

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

Five times.

Input Loop

You don't have to have five statements each using scan.nextLine(). You can use a loop to execute it the required number of times. Here is a program that reads and echos the first five lines of a file:

import java.util.Scanner;

class MultiEcho
{
  public static void main ( String[] args ) 
  {
    String line;
    Scanner scan = new Scanner( System.in );
 
    int count = 1;
    while ( count <= 5 )
    { 
      System.out.println("Enter line" + count + ": ");
      line = scan.nextLine();
      System.out.println( "You typed: " + line );
      count = count + 1;
    }
  }
}

Here is the program working with an input file:

C:/users/default/JavaLessons>java MultiEcho < input.txt
Enter line1:
You typed: This is line one,
Enter line2:
You typed: this is line two,
Enter line3:
You typed: this is line three,
Enter line4:
You typed: this is line, uh... four,
Enter line5:
You typed: and this is the last line.

D:/users/default/JavaLessons>

QUESTION 6:

(Thought question: ) How would you send the output of this program to another file?