简体   繁体   中英

Scanner not printing correctly when printing anything else

public static void main(String[] args) throws FileNotFoundException{
    Scanner console = new Scanner(System.in);
    readFile(console.next()); 
}

public static void readFile(String name) throws FileNotFoundException{
    Scanner input = new Scanner(new File("names.txt")); // Open pipe
    while(input.hasNextLine()){
        String line = input.nextLine();
        scanLine(line, name);
    }
}

public static void scanLine(String line, String name) throws FileNotFoundException{
    Scanner oneLine = new Scanner(line);
    String txtName = oneLine.next();
    System.out.println("txtName: " + txtName);
    System.out.println("name: " + name);
}

With Line 18 (Printing name); Response: [Incorrect]

txtName: Delvin
name: A
txtName: Demarco
name: A
txtName: Demarcus
name: A
txtName: Demario
name: A
....

Without Line 18: Response: [Correct]

txtName: A
txtName: Aaliyah
txtName: Aaron
txtName: Abagail
txtName: Abbey
txtName: Abbie
txtName: Abbigail
txtName: Abby
txtName: Abdiel
txtName: Abdul
txtName: Abdullah
txtName: Abe
txtName: Abel
....

This is how the code flows:

  1. User enters a String (a Name)
  2. readFile is called, I create a new Scanner object and pass in a new File .
  3. I want the application to keep running until it gets to the last line of the .txt file, so while the input has a nextLine, It'll keep looping.
  4. I pass in the string from a single row to scanLine, and I create a new Scanner object for that String.
  5. Each line looks like: String [Name], Int [Number], Int, Int, Int ...
  6. After it finds the line which matches with the name name the user entered, It'd then send that line to getStats() [That's it so far.]

Problem: For some reason, just printing the name variable (Line 18) oneLine.next() seems to start printing somewhere like half-way down the .txt file.

But if I don't print the name, (or don't use the name variable at all) -- It seems to work perfectly, printing the first letter A to the last.

Problem: For some reason, just printing the name variable (Line 18) oneLine.next() seems to start printing somewhere like half-way down the .txt file.

Whether running in a Windows console or running in an IDE (like Eclipse), the output window is limited to how many lines it can show.

When you print 2 lines per line of input, you're overflowing the output window, and the first half(?) of the output get discarded. It still got printed, it just scrolled off before you saw it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM