簡體   English   中英

不知道如何創建這個程序

[英]Can not figure out how to create this program

設計一個讀取文件名的程序。 程序將從該文件中讀取由空格分隔的字符串列表。 這些字符串將被轉換為它們的十進制等效值並求平均值。 然后程序會將結果輸出到另一個文件。

該程序還應該能夠優雅地處理輸入錯誤,例如錯誤的文件名或不包含十進制值的字符串數據。

似乎無法弄清楚如何做'程序將讀取由空格分隔的字符串列表。 這些字符串將被轉換為它們的十進制等效值並求平均值。 然后程序會將結果輸出到另一個文件。

“該程序還應該能夠優雅地處理輸入錯誤,例如錯誤的文件名或不包含十進制值的字符串數據。”

如果有人可以解釋或指導我在哪里可以找到這些示例,我將非常感激。

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)); 
       } 
    } 
}

您尋找的示例遍布 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數據類型;
    • 平均變量聲明為double數據類型;
    • for循環遍歷字符串數組;
      • 使用 String#matches( "-?\\\\d+(\\\\.\\\\d+)" ) 方法確保每個 Array 元素都是十進制值;
      • 將每個數組元素轉換為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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM