【问题标题】:Can not figure out how to create this program不知道如何创建这个程序
【发布时间】:2019-04-21 14:42:06
【问题描述】:

设计一个读取文件名的程序。程序将从该文件中读取以空格分隔的字符串列表。这些字符串将被转换为其十进制等效值并取平均值。然后程序会将结果输出到另一个文件。

程序还应该能够优雅地处理输入错误,例如错误的文件名或不包含十进制值的字符串数据。

似乎无法弄清楚如何做'程序将读取以空格分隔的字符串列表。这些字符串将被转换为其十进制等效值并取平均值。然后程序会将结果输出到另一个文件。'

'程序还应该能够优雅地处理输入错误,例如错误的文件名或不包含十进制值的字符串数据。'

如果有人能解释或指导我在哪里可以找到这些示例,我将非常感激。

public static void main (String [] args) throws Exception{

    //Create a Scanner object
    Scanner input = new Scanner (System.in);

    //prompt the user to enter a file name
    System.out.println("Enter a file name: ");
    File file = new File (input.nextLine());  

    // Read text from file and change oldString to newString 
    try ( 
        // Create input file 
        Scanner input = new Scanner(file); 
    ) { 
        while (input.hasNext()) { 
            String s1 = input.nextLine(); 
            list.add(s1.replaceAll(args[1], args[2])); 
        } 
    } 


    // Save the change into the original file 
    try ( 
        // Create output file 
        PrintWriter output = new PrintWriter(file); 
    ) { 
        for (int i = 0; i < list.size(); i++) { 
            output.println(list.get(i)); 
       } 
    } 
}

【问题讨论】:

    标签: java file input output


    【解决方案1】:

    您寻找的示例遍布 StackOverflow。你只需要选择一个特定的问题并研究它。

    在创建控制台应用程序时,您应该尝试使其尽可能用户友好,因为控制台在几乎所有方面都相当有限。当提示用户输入时,如果出现输入错误,允许用户多次尝试。 while 循环通常用于这种事情,这里是一个例子:

    //Create a Scanner object
    Scanner input = new Scanner(System.in);
    
    System.out.println("This application will read the file name you supply and");
    System.out.println("average the scores on each file line. It will then write");
    System.out.println("the results to another file you also supply the name for:");
    System.out.println("Hit the ENTER Key to continue (or q to quit)....");
    String in = "";
    while (in.equals("")) {
        in = input.nextLine();
        if (in.equalsIgnoreCase("q")) {
            System.out.println("Bye-Bye");
            System.exit(0);
        }
        break;
    }
    
    // Prompt the user to enter a file name
    String fileName = "";
    File file = null;
    while (fileName.equals("")) {
        System.out.println("Enter a file name (q to quit): ");
        fileName = input.nextLine();
        if (fileName.equalsIgnoreCase("q")) {
            System.out.println("Bye-Bye");
            System.exit(0);  // Quit Application
        }
        // If just ENTER key was hit 
        if (fileName.equals(""))  {
            System.out.println("Invalid File Name Provided! Try Again.");
            continue;
        }
        file = new File(fileName);
        // Does the supplied file exist? 
        if (!file.exists()) {
            // Nope!
            System.out.println("Invalid File Name Provided! Can Not Locate File! Try Again.");
            fileName = ""; // Make fileName hold Null String ("") to continue loop
        }
    }
    

    至于向用户询问文件名,上面的代码是一种更友好的方法。首先,它基本上解释了应用程序的作用,然后它允许用户在他/她愿意的情况下退出应用程序,并且它允许用户在输入错误或看起来有效的输入实际上是有效的输入时提供正确的输入发现有问题,例如找不到特定文件时。

    同样的概念应该适用于您的控制台应用程序的所有方面。底线是,您创建了应用程序,因此您知道预期的内容,但是对于要使用您的应用程序的人来说不能这样说。他们完全不知道会发生什么。

    对于手头的任务,您应该利用已经学习过的代码和概念,以及通过研究和试验其他算法代码概念来学习尚未学习的代码和概念。在此过程中,您会跳出某种程度的“跳出框框思考”,随着您最终学习的代码和概念越多,这种特性实际上会变得自然。

    写下完成任务的有条不紊的进攻计划。随着代码的进展,这可以为您节省大量的痛苦,例如:

    • 解释申请;
    • 向用户询问文件名;
      • 确保提供了文件名;
        • 如果没有,则再次询问文件名;
      • 确保文件存在;
        • 如果没有,则再次询问文件名;
    • 向用户询问输出文件名;
      • 查看文件是否已经存在;
        • 如果有,请询问是否覆盖;
        • 如果不覆盖,则要求另一个输出文件名;
    • 打开阅读器以读取提供的文件名;
    • 打开 Writer 将结果写入指定文件名;
    • 使用 while 循环读取每个文件行;
      • 使用 String.split("\\s+") 方法将每个读取的行拆分为字符串数组;
      • totalSum 变量声明为 double 数据类型;
      • average 变量声明为 double 数据类型;
      • 使用 for 循环遍历字符串数组;
        • 确保每个数组元素都是十进制值,使用 String#matches("-?\\d+(\\.\\d+)") 方法;
        • 将每个数组元素转换为 double 并添加到 **totalSum*;
      • for 循环之后,将 totalSum 除以中的元素数 要获取平均值的数组,将此数量放入 average 变量中;
      • 写入文件:“平均值为:” + fileLine + “是:” + 平均值。还 显示到控制台;
    • 处理完整个文件后,关闭 Reader 并关闭 Writer。
    • 完成。

    现在这将是您创建应用程序的基本指南。

    使用 Scanner 读取数据文件时,我觉得最好在 while 循环条件中使用 Scanner#hasNextLine() 方法而不是 Scanner#hasNext() 方法,因为这种方法更侧重于获取令牌而不是文件行。所以我认为这将是一个更好的方法:

    String outFile = "";
    // Write code to get the File Name to write to and place 
    // it into the the variable outFile ....
    File outputFile = new File(outFile); // True file name is acquired from User input
    if (outputFile.exists()) {
        // Ask User if he/she wants to overwrite if file exists....and so on
    }
    
    // 'Try With Resourses' on reader
    try (Scanner reader = new Scanner(file)) {
        // 'Try With Resourses' on writer
        try (PrintWriter writer = new PrintWriter(outputFile)) {
            String line = "";
            while (reader.hasNextLine()) {
                line = reader.nextLine().trim();
                // Skip blank lines (if any)
                if (line.equals("")) {
                    continue;
                }
                // Split the data line into a String Array
                String[] data = line.split("\\s+"); // split data on one or more whitespaces
                double totalSum = 0.0d;  // Hold total of all values in data line
                double average = 0.0d;   // To hold the calculated avarage for data line
                int validCount = 0;      // The amount of valid data values on data line (used as divisor)
                // Iterate through data Line values String Array
                for (int i = 0; i < data.length; i++) {
                    // Is current array element a string representation of
                    // a decimal value (signed or unsigned)
                    if (data[i].matches("-?\\d+(\\.\\d+)")) {
                        // YES!...add to totalSum
                        validCount++;
                        // Convert Array element to double then add to totalSum.
                        totalSum += Double.parseDouble(data[i]); 
                    }
                    else {
                        // NO! Kindly Inform User and don't add to totalSum.
                        System.out.println("An invalid value (" + data[i] + ") was detected within "
                                + "the file line: " + line);
                        System.out.println("This invalid value was ignored during                                   + "averaging calculations!" + System.lineSeparator());
                    }
                }
                // Calculate Data Line Average
                average = totalSum / validCount;
                // Write the current Data Line and its' determined Average
                // to the desired file (delimited with the Pipe (|) character.
                writer.append(line + " | Average: " + String.valueOf(average) + System.lineSeparator());
                writer.flush();
            }
        }
        System.out.println("DONE! See the results file.");
    }
    // Catch the fileNotFound exception
    catch (FileNotFoundException ex) {
        ex.printStackTrace();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-02
      • 2020-10-23
      • 2023-03-25
      • 2019-12-13
      • 1970-01-01
      相关资源
      最近更新 更多