Если я прошу пользователя ввести файл, а файл не существует, как я могу продолжать запрашивать имя файла без остановки программы? - PullRequest
0 голосов
/ 03 апреля 2020

Это то, что у меня есть ... Я знаю, что для этого потребуется al oop или, возможно, метод .empty () из класса File, но я не уверен ... любая помощь приветствуется. То, что у меня есть, откроет файл, прочитает из файла в каждой строке, а затем вернет обратно количество символов в файле, количество слов в файле и количество предложений в файле.

public class FileExample{
    public static void main(String[] args) throws FileNotFoundException, IOException{
        Scanner in = new Scanner(System.in);
        boolean fileFound = false;
        try{
            System.out.println("What is the name of the file?");
            inputFile = in.nextLine();
            File file = new File(inputFile);
            fileFound = file.exists();
            FileInputStream fileStream = new FileInputStream(file); 
            InputStreamReader input = new InputStreamReader(fileStream);
            BufferedReader reader = new BufferedReader(input);
            if(!file.exists()){

            }
            while((line = reader.readLine()) != null){
                if(!(line.equals(""))){
                    ...
                }
            }
        }
        catch(FileNotFoundException e){
            System.out.println("File not found.");
        }
        System.out.println("output data");
    }   
}

Ответы [ 3 ]

0 голосов
/ 03 апреля 2020

Используйте некоторое время l oop, пока файл не существует. Пример:

...
System.out.println("What is the name of the file?");
inputFile = in.nextLine();
File file = new File(inputFile);
fileFound = file.exists();
while(!fileFound){
    System.out.println("The file does not exist. What is the name of the file?");
    inputFile = in.nextLine();
    file = new File(inputFile);
    fileFound = file.exists();
}
FileInputStream fileStream = new FileInputStream(file); 
InputStreamReader input = new InputStreamReader(fileStream);
BufferedReader reader = new BufferedReader(input);
...
0 голосов
/ 03 апреля 2020

Добавьте do-while в свой код. Нравится. не совсем уверен, что это будет работать, но я надеюсь, что вы поняли идею

do {
    try {
        System.out.println("What is the name of the file?");
        inputFile = in.nextLine();
        File file = new File(inputFile);
        fileFound = file.exists();
        FileInputStream fileStream = new FileInputStream(file); 
        InputStreamReader input = new InputStreamReader(fileStream);
        BufferedReader reader = new BufferedReader(input);

        while((line = reader.readLine()) != null){
            if(!(line.equals(""))){
                characterCount += line.length();
                String[] wordList = line.split("\\s+");
                countWord += wordList.length;
                String[] sentenseList = line.split("[!?.:]+");
                sentenseCount += sentenseList.length;
            }
        }
    } catch (FileNotFoundException e){
        System.out.println("File not found.");
    }
} while (!fileFound) {
    System.out.println("Character count: "+characterCount);
    System.out.println("Word count: "+countWord);
    System.out.println("Sentence count: "+sentenseCount);
}
0 голосов
/ 03 апреля 2020

Вам нужно сделать некоторое время l oop и переместить блок try внутрь l oop.

while(true){
    try{
        System.out.println("What is the name of the file?");
        inputFile = in.nextLine();
        File file = new File(inputFile);
        if(!file.exists()){
            continue;
        }
        FileInputStream fileStream = new FileInputStream(file); 
        InputStreamReader input = new InputStreamReader(fileStream);
        BufferedReader reader = new BufferedReader(input);
        while((line = reader.readLine()) != null){
            if(!(line.equals(""))){
                characterCount += line.length();
                String[] wordList = line.split("\\s+");
                countWord += wordList.length;
                String[] sentenseList = line.split("[!?.:]+");
                sentenseCount += sentenseList.length;
            }
        }
        break;
    }
    catch(FileNotFoundException e){
        System.out.println("File not found.");
    }
}
...