1

How would I print the elements in this case, words from a file. My program currently takes input from a file called input with contains the words "one two three four galumph" just like that. As of right now, it list each word on a separate line and once it reaches "galumph" it terminates, which is what I want, but I would also like for it to displays all the elements in the file before anything. How would I do that? I tried doing a while loop at the very beginning, but get errors. Any suggestions?

import java.io.*;
import java.util.Scanner;
class EchoWords {

public static void main(String[] args) throws FileNotFoundException {
String word;
String line;
try {
      File file = new File("input");
      Scanner s2 = new Scanner(file);

while(s2.hasNext()) {
     String s = s2.next();
     System.out.println(s);

while(true) {
     word = s2.next();
if(word.equals("galumph")) {
     break;
}else{
     System.out.println(word);
     continue;
     }
    }
    System.out.println("bye!");
   }
} catch (FileNotFoundException e) {
     e.printStackTrace();
    }
  }
}
HPotter
  • 131
  • 2
  • 11

1 Answers1

1

If your file is not too big you could read all lines of the file at once and store them in a List:

String fileName = "filePath";
List<String> allLines = Files.readAllLines( Paths.get( fileName ) );

You can then iterate through the lines at will:

//print all the lines
 for ( String line : allLines )
 {
      System.out.println( line );
 }

 //print until galumph
 for ( String line : allLines )
 {
     if ( "galumph".equals( line ) )
     {
          break;
     }
     else
     {
          System.out.println( line );
     }

 }

This approach has the benefit that you need to read your file only once.

Rhayene
  • 565
  • 6
  • 18