简体   繁体   中英

How do I ask a user for a input file name, and then use that file name?

I am trying to ask the user for the name of their file, then I am going to scan the file to see how many indices are in the file, and then put it in an array and go from there.

Here is my code:

import java.util.*;        
import java.io.*;

public class TestScoresAndSummaryStatistics {
     public static void main(String[] args) throws IOException {
        int scores;
        int indices = -1;
        Scanner keyboard = new Scanner(System.in);

        System.out.println("Enter the name of the file");
        String fileName = keyboard.next();

        //I believe something is wrong here, am I incorrectly bring inputFile into new File?
        File inputFile = new File(fileName);
        Scanner data = new Scanner(inputFile);

        while (data.hasNext()) {
            indices++;
        }
        System.out.println("There are: " + indices + "indices.");
    }
}

I believe something went wrong with the = new File(filename); part: maybe because I didn't have quotes, but I'm not exactly sure. How can I fix this?

You only check if there is data in Scanner but you never consume it.

The java.util.Scanner.hasNext() method Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.

The below code will never end if there is any data in file, you increase your counter with out reading the data.

   while (data.hasNext()) {
        indices++;
    }

Solution:

Change

while (data.hasNext()) {
    indices++;
}

to

while (data.hasNext()) {
    indices++;
    data.next();
}

Explanation:

You want to increment indices for every line. To achieve this, you should go to the next line and check if there are other available lines. Q: How can you go to the next line ? A: data.next();

Eg - file.txt:

Your approach - bad :

  • Step 1

     line a <--- here you are line b line c 
  • Step 2

     line a <--- here you are line b line c 

...

data.hasNext() will be true forever because you will be on the first line at every step => infinite loop

Correct approach:

  • Step 1

     line a <--- here you are line b line c 
  • Step 2

     line a line b <--- here you are line c 
  • Step 3

     line a line b line c <--- here you are 

In this case data.hasNext() will return true only 3 times, then it will return false ( the file doesn't have any line after the 3rd line )

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