簡體   English   中英

需要幫助找到平均值並打印出錯誤

[英]Need help finding average and printing out errors

我需要幫助解決這個學校問題。 如果您有興趣,請訪問以下鏈接: http : //go.code-check.org/codecheck/files/14121519036ltx4u6e3i9mtrqynsyhgihr7

當我嘗試解決問題時,我會打印正確的消息,但是有問題。 我懷疑在Codecheck的驅動程序中是類似System.out.println(“ Average =” + message);之類的東西。 所以,我最終得到的結果是

平均值= squeeze.txt沒有數字數據

這不是我想要的。 如果驅動程序給了我這個問題,我應該如何解決? 這是我目前所擁有的:

import java.io.*;

import java.util.*;

public class Average {

    double total = 0;
    int count = 0;
    Scanner in;
    String myName;
    public Average(String name){
        myName = name;
        try{
            in = new Scanner(new File(name));
        }
        catch (Exception e){
            System.out.println("Error: " + myName + " (The system cannot find the file specified)");
        }
    }

    public String scanDataAndCalculateAverage(){
        try{
            if (!in.hasNext())
                throw new Exception(myName + " is empty");
            else 
                while (in.hasNextLong()){
                    total += in.nextLong();
                    count++;
                }
            if (in.hasNext()){
                throw new Exception(myName + " does not have numerical data");
            }
            else return "" + (total / count);
        }
        catch (Exception e){
            return e.getMessage();
        }
    }

}

編輯:我的新構造函數:

公共平均值(字符串名稱)引發異常{

    myName = name;
    try{
        in = new Scanner(new File(name));
    }
    catch (Exception e){
        throw new Exception("Error: " + myName + " (No such file or directory)");
    }
}

看起來輸入文件包含的內容不是有效的long。 看到您有以下幾行:

while (in.hasNextLong()){
    total += in.nextLong(); 
    count++;
}
if (in.hasNext()){
    throw new Exception(myName + " does not have numerical data");
}

因此,如果文件中的內容與long不同,則將退出循環,然后if將向您發送您發布的消息。

要查找導致問題的確切原因,請更改此行:

throw new Exception(myName + " does not have numerical data");

對此:

throw new Exception(myName + " does not have numerical data: (" + in.next() + ")");

您的代碼存在以下問題:

catch (Exception e) {
    return e.getMessage();
}

您正在捕獲任何異常,並以字符串形式返回消息。 因此,方法scanDataAndCalculateAverage的調用“通常”完成,並且“代碼檢查器”在返回的String前面寫入Average = ,因為它認為您的程序返回了有效值。

您需要將Exception傳播到調用方法,以便它知道出了點問題。

由於這似乎是一項任務,因此應該嘗試解決該問題。 如果您對此有疑問,請發表評論。

順便說一句,請更改以下異常消息:

  1. "Error: " + myName + " (The system cannot find the file specified)"應為"Error: " + myName + " (No such file or directory)"
  2. myName + " does not have numerical data"應該是myName + "does not have numeric data"

如果您使用郵件,則支票不會通過。 奇怪,作業中提到了第一個,但是它使用了另一個來進行檢查。

這是整個檢查的預期輸出:

Average = 49.91791791791792
squeeze.txt does not have numeric data
empty.txt is empty
Error: notThere.txt (No such file or directory)
Average = 0.0

暫無
暫無

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

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