簡體   English   中英

用Java寫入/讀取文件

[英]Write/Reading Files in Java

我正在分配作業,無法使用此方法將正確的輸出輸出到文件。 我應該得到平均值並將其寫入文件。 它們是StatsDemo類和StatsFile類。 我是Java的初學者,所以我只需要一點幫助。 我在StatsFile類中的方法當前是這樣的:

//returns the calculated arithmetic average
public double calculateMean(String filename) throws FileNotFoundException
{
    // declare variables step 5
    double accumulator = 0.0;
    int counter =0;
    String line;
    try{
    File input = new File(filename);
    //create a Scanner object passing it the File object
    Scanner keyboard = new Scanner(input);
    //for (int i = 0; i < input.length(); i++){
         // Read a double from the file.
    while(keyboard.hasNextDouble()){
         accumulator += keyboard.nextDouble();

         // Add to counter
         counter++;
    }
    keyboard.close();


}catch(FileNotFoundException e){
    }
    return (accumulator/counter);
}

演示是這樣的:

import java.util.Scanner;
import java.text.DecimalFormat;
import java.io.*;
public class StatsDemo {

    public static void main(String[] args) throws FileNotFoundException  {
        // TODO Auto-generated method stub

        DecimalFormat threeDec  = new DecimalFormat("0.000");
        Scanner keyboard = new Scanner(System.in);

        String filename; // the user input file name

        System.out.print("Enter the file name: ");
        filename = keyboard.nextLine();


        FileStats fileObj = new FileStats(filename); 

        try{
            PrintWriter name = new PrintWriter("Results.txt");
            name.println("mean = " + threeDec.format(fileObj.getMean()));
            name.println("Standard Deviation = " + threeDec.format(fileObj.getStdDev()));

            name.close();
        }catch(IOException e){
            System.out.println("Error");
        }
    }
}

捕捉和拋出仍然使我感到困惑。 我的問題是,當我打開文件時,它給了我一個問號,而不是平均值。 任何幫助將不勝感激。

如果try塊中發生異常,則控制跳至catch塊。 您應該考慮在這種情況下會發生什么。 您可能可以糾正問題並繼續; 您可能希望查看問題,重新拋出和異常,或者您只希望讓呼叫者處理問題。 在最后一種情況下,您根本不需要捕獲,只需要對方法聲明進行throws

捕獲異常而不采取任何措施很少是一個好主意,因為問題只是被忽略了。 請記住,除非拋出另一個異常,否則代碼流將在catch子句之后進行,因此,如果文件不存在,您仍將處理return (accumulator/counter) ,這不是您想要的。

查看您的代碼,您的方法已經引發了FileNotFoundException,因此只需刪除try和catch。

暫無
暫無

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

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