go to previous page   go to home page   go to next page

Answer:

Five times.


Input Loop

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;
    }
  }
}

You can use a loop to execute scan.nextLine() the required number of times. The above program reads and echoes the first five lines of a file. Here is the program working with an input file:

C:\temp>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, four,
Enter line5:
You typed: and this is the last line.

D:\temp>

If the input file has fewer than five lines nextLine() will throw an Exception and the program will halt. Dealing with Exceptions is a future topic.


QUESTION 6:

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