java - 如何将在循环中查找文件的 Try-catch 语句放入其中?

标签 java

我需要将我的文件搜索放在我的 readData() 方法中的一个循环中,该循环捕获未找到的异常,然后循环再次提示用户输入文件名,直到找到正确的文件名已输入。输入正确的文件名后,返回值就会传递给其他方法以继续执行代码。

我尝试将代码块放入 do-while 方法中,但它会导致无限循环。我需要有关此语义的帮助。

private static ArrayList<Double> readData() {
        ArrayList<Double> inputValues = new ArrayList<>();
        String inputFileName;           
        double value;           
        Scanner input = new Scanner(System.in);                    
        System.out.print("Enter the name of the input file: ");                    
        inputFileName = input.nextLine();          
        File file = new File(inputFileName);                         
          do{  
            try {
                input = new Scanner(file);
                while (input.hasNextDouble()) {
                    value = input.nextDouble();
                    inputValues.add(value);
                }
            } 
            catch (FileNotFoundException e) {
                System.out.println("File not found!");
                System.out.println("Please enter file name again: ");                                       
            }
        }
        while(!file.exists());
        return inputValues;
}

我希望这能解释“找不到文件!”然后再次提示输入文件名,直到输入正确的文件名。然而,它只执行一次 try-catch,然后尝试返回 inputValues 返回值。这会导致程序崩溃。

我尝试过 do while 循环。但最终陷入无限循环

package weightedavgdataanalyzer;

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

public class WeightedAvgDataAnalyzer {

    public static void main(String[] args) {
            ArrayList<Double> inputValues = readData();
            double weightedAvg = calcWeightedAvg(inputValues);
            printResults(inputValues, weightedAvg);
    }
    private static void printResults(ArrayList<Double> inputValues, double weightedAvg) {
            System.out.print("Enter output file name: ");
            Scanner input = new Scanner(System.in);
            String outputFile = input.nextLine();
            try {
                    PrintWriter writer = new PrintWriter(outputFile);
                    writer.print("The weighted average of the numbers is " + weightedAvg + ", when using the data ");
                    for (int i = 2; i < inputValues.size(); i++) {
                            writer.print(inputValues.get(i) + ", ");
                    }                 
                    writer.println("where " + inputValues.get(0)
                                    + " is the weight used, and the average is computed after dropping the lowest "
                                    + Integer.valueOf((int) inputValues.get(1).doubleValue()) + " values.");
                    writer.close();
            } 
            catch (FileNotFoundException e) {
               e.printStackTrace();     
            }
    }
    private static double calcWeightedAvg(ArrayList<Double> inputValues) {
            double sum = 0;
            double average;
            double weight = inputValues.get(0);
            int toDrop = Integer.valueOf((int) inputValues.get(1).doubleValue());
            ArrayList<Double> newList = new ArrayList<>();
            for (int i = 2; i < inputValues.size(); i++) {
                    newList.add(inputValues.get(i));
            }                  
            Collections.sort(newList);
            for (int i = (toDrop); i < newList.size(); i++) {
                    sum += weight * newList.get(i);
            }
            average = sum / (newList.size() - toDrop);         
            return average;
    }

    private static ArrayList<Double> readData() {
            ArrayList<Double> inputValues = new ArrayList<>();
            String inputFileName;           
            double value;           
            Scanner input = new Scanner(System.in);                    
            System.out.print("Enter the name of the input file: ");                    
            inputFileName = input.nextLine();          
            File file = new File(inputFileName);                         
              do{  
                try {
                    input = new Scanner(file);
                    while (input.hasNextDouble()) {
                        value = input.nextDouble();
                        inputValues.add(value);
                    }
                } 
                catch (FileNotFoundException e) {
                    System.out.println("File not found!");
                    System.out.println("Please enter file name again: ");                                       
                }
            }
            while(!file.exists());
            return inputValues;
    }
}

最佳答案

File file = new File(inputFileName); 的初始化移至循环内以及“询问新文件名行”。最后一步是检查该文件是否是一个目录。您无法使用 Scanner 读取目录,但 file.exists() 仍将返回 true

private static ArrayList<Double> readData() {
    ArrayList<Double> inputValues = new ArrayList<>();
    String inputFileName;
    double value;
    Scanner input = new Scanner(System.in);
    File file;
    System.out.print("Enter the name of the input file: ");
    do {
        inputFileName = input.nextLine();
        file = new File(inputFileName);
        try {
            input = new Scanner(file);
            while (input.hasNextDouble()) {
                value = input.nextDouble();
                inputValues.add(value);
            }
        } catch (FileNotFoundException e) {
            System.out.println("File not found!");
            System.out.println("Please enter file name again: ");
        }
    } while (!file.exists() && !file.isDirectory());
    return inputValues;
}

关于java - 如何将在循环中查找文件的 Try-catch 语句放入其中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57292531/

相关文章:

Eclipse 中的 Java 分析 - 调用堆栈

java - 有谁知道使用构建器模式包装 JOptionPane 的代码?

java - 骰子滚动战斗系统

java - 如何直接从ftl模板调用FreeMarker指令?

java - Groovy 文字正则表达式/\\/未编译

java - 处理 DATETIME 值 0000-00-00 00 :00:00 in JDBC

java - 警告 : "The following classpath entry <address> will not be available on the server' s classpath"

java - 了解 jar 命令行

java - Excel correl() 函数与java?

java - 使用play-framework 2.5连接MySQL数据库