Search code examples
javajava.util.scannerstring-parsing

Java printing output of text file and checking first character


I think the commented out section of my code works. My issue is when I print out the string "s" I only get the last line of my text file.

import java.io.File; 
import java.util.Scanner; 
public class mainCode {
    public static void main(String[] args)throws Exception 
      { 
          // We need to provide file path as the parameter: 
          // double backquote is to avoid compiler interpret words 
          // like \test as \t (ie. as a escape sequence) 
          File file = new File("F:\\Java Workspaces\\Workspace\\Files\\file.txt"); 

            Scanner sc = new Scanner(file); 
            String s = new String("");

            while (sc.hasNextLine())
                s = sc.nextLine();
                System.out.println(s);
//                if (s.substring(0,1).equals("p") || s.substring(0,1).equals("a") ){
//                    System.out.println(s);
//                }
//                else{
//                    System.out.println("Error File Format Incorrect");
//                }
      }
}

The output is just "a192" the lines before are "a191" and "a190"


Solution

  • Your indentation makes it look like your while executes multiple statements, but it doesn't. Use braces to enclose statements you want to execute as a block.

            while (sc.hasNextLine())
                s = sc.nextLine();
            System.out.println(s);  // proper indentation
    

    Probably what you want:

      while( sc.hasNextLine() ) {
         s = sc.nextLine();
         System.out.println( s );
      }
    

    (I had to drop this into my IDE to find it. My IDE labeled that second line as "Confusing Indentation" for me. Good IDEs do that.)