简体   繁体   中英

I am wishing to ask the user to input a .txt file name, and re-prompt the user if the file name does not exist. How is this possible?

I am wishing to ask the user to input a .txt file name, and re-prompt the user if the file name does not exist. Below is the code that I have written to open a .txt file which has within it 10 numbers and average the numbers. If the initial user input file name is correct, the program executes as it should, but, if the input filename is incorrect, and the user then inputs the CORRECT file name as prompted, the program will continue prompt the user for a correct file name. How can this be fixed? Many thanks.

import java.io.*;
import java.util.Scanner;
public class Test {
    public static void main(String[] args) throws FileNotFoundException{

    Scanner console = new Scanner(System.in);
    System.out.println("Please enter below the name of the file you wish to import.");
    boolean flag = true;
    String fname = console.nextLine();
    File inFile = new File (fname);

    System.out.println("\nExists Returns: "+inFile.exists());
    System.out.println("\ncanRead Returns: "+inFile.canRead());
    System.out.println("\ngetAbsolutePath Returns: "+inFile.getAbsolutePath());
    while (flag){   
        while(!inFile.exists()){
            System.out.println("\nError: File Not Found. Try Again.");
            fname = console.nextLine();
            flag = true;
        }
        if (inFile.exists()){
            flag = false;    
            Scanner filescan = new Scanner(inFile);
            double sum = 0;
            for (int i = 1; i <=10; i++){
                double next = filescan.nextDouble();
                System.out.println("Grade "+i+" = "+next);
                sum += next;
            }
            System.out.println("\nAverage Grade = "+(sum/10)+"%");
        }
    }
}

}

This while loop: while (flag){ is unnecessary.

If you remove it (and it's corresponding } ), you will have a loop that waits until the user has entered a valid file, then you will have code that processes a valid file, then the program will finish.

Edit : As @OleVV points out below, you also need to set File inFile = new File (fname); again after fname = console.nextLine(); .

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