Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 无法确定如何创建此程序_Java_File_Input_Output - Fatal编程技术网

Java 无法确定如何创建此程序

Java 无法确定如何创建此程序,java,file,input,output,Java,File,Input,Output,设计一个以文件名读取的程序。程序将从该文件中读取由空格分隔的字符串列表。这些字符串将转换为其十进制等效值并求平均值。然后程序将结果输出到另一个文件 该程序还应该能够优雅地处理输入错误,例如错误的文件名或不包含十进制值的字符串数据 似乎无法理解如何执行“程序将读取由空格分隔的字符串列表”。这些字符串将转换为其十进制等效值并求平均值。然后程序将结果输出到另一个文件中。” 及 “该程序还应该能够优雅地处理输入错误,例如错误的文件名或不包含十进制值的字符串数据。” 如果有人能解释或指导我在哪里可以找到这

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

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

似乎无法理解如何执行“程序将读取由空格分隔的字符串列表”。这些字符串将转换为其十进制等效值并求平均值。然后程序将结果输出到另一个文件中。”

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

如果有人能解释或指导我在哪里可以找到这些例子,我将不胜感激

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)); 
       } 
    } 
}
publicstaticvoidmain(字符串[]args)引发异常{
//创建扫描仪对象
扫描仪输入=新扫描仪(System.in);
//提示用户输入文件名
System.out.println(“输入文件名:”);
File File=新文件(input.nextLine());
//从文件中读取文本并将oldString更改为newString
试试(
//创建输入文件
扫描仪输入=新扫描仪(文件);
) { 
while(input.hasNext()){
字符串s1=input.nextLine();
list.add(s1.replaceAll(args[1],args[2]);
} 
} 
//将更改保存到原始文件中
试试(
//创建输出文件
PrintWriter输出=新的PrintWriter(文件);
) { 
对于(inti=0;i
你要找的例子到处都是。你只需要选择一个特定的问题并进行研究

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

//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
    }
}
至于询问用户文件名,上面的代码是一种更友好的方法。首先,它基本上解释了应用程序的功能,然后允许用户在他/她愿意的情况下退出应用程序,并允许用户在出现错误的条目时提供正确的条目,或者如果实际发现某个看似有效的条目有错误,例如无法找到特定文件时

同样的概念应该应用于控制台应用程序的所有方面。底线是,您创建了应用程序,因此您知道预期的结果,但是对于使用您的应用程序的人来说,情况并非如此。他们完全不知道会发生什么

对于手头的任务,您需要利用您已经学习的代码和概念,对于那些您还没有通过研究和实验其他算法代码概念来学习的代码和概念。在这个过程中,你会满怀希望地学会某种程度的“跳出框框思考”,随着你最终学习到更多的代码和概念,这种特质实际上会变得自然

写下完成任务的有条理的攻击计划。这可以在代码开发过程中为您节省大量的痛苦,例如:

  • 解释应用
  • 向用户询问文件名;
    • 确保提供了文件名;
      • 如果没有,则再次询问文件名
    • 确保文件存在;
      • 如果没有,则再次询问文件名
  • 要求用户输入输出文件名;
    • 查看文件是否已经存在;
      • 如果覆盖,则请求覆盖
      • 如果不覆盖,则要求另一个输出文件名
  • 打开读卡器以读取提供的文件名
  • 打开写入程序,将结果写入指定的文件名
  • 使用while循环读取每个文件行;
    • 使用String.Split(
      “\\s+”
      )方法将每个读入行拆分为字符串数组
    • 将一个totalSum变量声明为double数据类型
    • 平均值变量声明为双重数据类型
    • 使用循环遍历字符串数组;
      • 使用 字符串匹配(
        “-?\\d+(\\.\\d+)”
        )方法
      • 将每个数组元素转换为double并添加到**totalSum*
    • for循环之后,将totalSum除以 数组以获得平均值,将此金额放入平均值变量中
    • 写入文件:“+fileLine+”的平均值为:“+Average”。阿尔索 显示到控制台
  • 处理完整个文件后,关闭读卡器和写卡器
  • 完成了
这将是创建应用程序的基本指南

当使用扫描仪读取数据文件时,我觉得最好在while循环条件下使用该方法,而不是使用该方法,因为该方法更侧重于获取令牌,而不是文件行。因此,我认为这是一个更好的方法:

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();
}
String outFile=“”;
//编写代码以获取要写入的文件名并放置
//将其导入变量outFile。。。。
文件输出文件=新文件(输出文件);//从用户输入中获取真实的文件名
if(outputFile.exists()){
//询问用户是否要覆盖文件是否存在……等等
}
//在reader上使用“资源试用”
尝试(扫描仪阅读器=新扫描仪(文件)){
//“试试看