简体   繁体   中英

Java Writer error: The method write(char[], int, int) in the type Writer is not applicable for the arguments (int, double, int, String)

I'm trying to write the output of my Java program to a file and I can't figure out the error I'm getting. Here's my code:

import java.io.*;
import java.nio.file.Paths;
import java.util.*;

public class Program10 
{ 
    public static Writer wr;
    public Scanner input;
    static ArrayList<Household> surveyData = new ArrayList<Household>();
    static double avg;
    
    public static void main(String[] args)
    {
        Program10 obj = new Program10(); 
        developerInfo();
        obj.readFile();
        obj.outputRecords(surveyData);
        obj.calculateAverage(surveyData);
        obj.exceedsAverage(surveyData);
        obj.belowAverage(surveyData);
        obj.belowAveragePercent(surveyData);
        //wr.close();
    }
    //**************************************************************
    //
    //  Method:       readFile
    // 
    //  Description:  reads the file and calculates average income
    //
    //  Parameters:   None
    //
    //  Returns:      N/A 
    //
    //**************************************************************
    public void readFile()
    {
        // Open the input file
        try 
        {
            input = new Scanner(Paths.get("Program10.txt"));
            System.out.println("Input file open.");
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
        // Open the output file
        try
        {
            **wr = new FileWriter("Program10-output.txt");**
            System.out.println("Output file open.");
        }
        catch(IOException e) 
        {
           System.err.println("Error handling output file. Terminating...");
           System.exit(1);
        }
        
        // Create ArrayList of Household Objects
        while (input.hasNext()) 
        {
            //reading each line of the input file
            int id = input.nextInt();
            double income = input.nextDouble();
            int members = input.nextInt();
            String state = input.nextLine();
            //creating the object by using the constructor
            Household house = new Household(id, income, members, state);
            //storing to Household variable
            surveyData.add(house);
            **wr.write(house.getID(), house.getIncome(), house.getMembers(), house.getState());**
            wr.write("\r\n");
        }
    }
    //***************************************************************
    //
    //  Method:       outputRecords
    // 
    //  Description:  Prints each Household record in four (4) columns
    //
    //  Parameters:   ArrayList<Household> surveyData
    //
    //  Returns:      N/A
    //
    //**************************************************************
    public static void outputRecords(ArrayList<Household> surveyData)
    {
        // Outputting ID, Income, Members & State in four (4) column format
        try
        {
            System.out.printf("%nIdentification\tIncome\t\tMembers\t\tState");
            wr.write("%nIdentification\tIncome\t\tMembers\t\tState");
            
            System.out.println();
            wr.write("\r\n");
            
            for (int i = 0; i < surveyData.size(); i++) 
            {
                Household data = surveyData.get(i);
                System.out.printf("%s%18s%11s%20s\n", data.getID() , data.getIncome() , data.getMembers(), data.getState());
                wr.write("%s%18s%11s%20s\n", data.getID() , data.getIncome() , data.getMembers(), data.getState());
            }
        }
        catch(IOException e) 
        {
            e.printStackTrace();
        }
    }

And my error reads: The method write(String, int, int) in the type Writer is not applicable for the arguments (String, int, double, int, String)

I don't understand where it's being defined that the writer is constructed as write(char[], int, int) when I first define it as follows: wr = new FileWriter("Program10-output.txt");

How can I define the writer object so as to write the household object in the format (int, double, int, String) to it?

You are trying to use write the way you use printf , but write can't be used that way. It doesn't support format strings. It doesn't matter how you declare wr . The problem is not in the declaration. Writer just doesn't have this functionality.

If you want to use a format, one way is to use String.format to first create the formatted string, then pass the formatted string to write .

String formattedString = String.format("%s%18s%11s%20s\n", data.getID() , data.getIncome() , data.getMembers(), data.getState());
wr.write(formattedString);

String.format works just like printf , except it returns the formatted string, rather than printing it to the console.

There seems to be other places you have used format strings. You should change those places to use String.format is.

the write() method on FileWriter is inherited from OutputStreamWriter. You can see the documentation here. https://docs.oracle.com/javase/7/docs/api/java/io/OutputStreamWriter.html#write(char[],%20int,%20int)

There are only 3 options for write() which will write a String to a file. I am unsure what you mean by write to the household object?.

Perhaps you may wish to override the to toString method in your Household object in which case you could write this as a string to your file.

You can Use String.format() where specify data format and write String to writer.

 import java.io.*;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Scanner;

public class Program10 {
    public static Writer wr;
    public Scanner input;
    static ArrayList<Household> surveyData = new ArrayList<Household>();
    static double avg;

    public static void main(String[] args) throws IOException {
        Program10 obj = new Program10();
        // developerInfo();
        obj.readFile();
        obj.outputRecords(surveyData);
        // obj.calculateAverage(surveyData);
        // obj.exceedsAverage(surveyData);
        // obj.belowAverage(surveyData);
        // obj.belowAveragePercent(surveyData);
        // wr.close();
    }

    // **************************************************************
    //
    // Method: readFile
    //
    // Description: reads the file and calculates average income
    //
    // Parameters: None
    //
    // Returns: N/A
    //
    // **************************************************************
    public void readFile() throws IOException {
        // Open the input file
        try {
            input = new Scanner(Paths.get("Program10.txt"));
            System.out.println("Input file open.");
        } catch (IOException e) {
            e.printStackTrace();
        }
        // Open the output file
        try {
            wr = new FileWriter("Program10-output.txt");
            System.out.println("Output file open.");
        } catch (IOException e) {
            System.err.println("Error handling output file. Terminating...");
            System.exit(1);
        }

        // Create ArrayList of Household Objects
        while (input.hasNext()) {
            // reading each line of the input file
            int id = input.nextInt();
            double income = input.nextDouble();
            int members = input.nextInt();
            String state = input.nextLine();
            // creating the object by using the constructor
            Household house = new Household(id, income, members, state);
            // storing to Household variable
            surveyData.add(house);
            String formattedString = String.format("%s%18s%11s%20s\n", house.getId(), house.getIncome(),
                    house.getMembers(), house.getState());
            wr.write(formattedString);
            wr.write("\r\n");
        }
    
    }

    // ***************************************************************
    //
    // Method: outputRecords
    //
    // Description: Prints each Household record in four (4) columns
    //
    // Parameters: ArrayList<Household> surveyData
    //
    // Returns: N/A
    //
    // **************************************************************
    public static void outputRecords(ArrayList<Household> surveyData) {
        // Outputting ID, Income, Members & State in four (4) column format
        try {
            System.out.printf("%nIdentification\tIncome\t\tMembers\t\tState");
            wr.write("%nIdentification\tIncome\t\tMembers\t\tState");

            System.out.println();
            wr.write("\r\n");

            for (int i = 0; i < surveyData.size(); i++) {
                Household data = surveyData.get(i);
                System.out.printf("%s%18s%11s%20s\n", data.getId(), data.getIncome(), data.getMembers(),
                        data.getState());
                wr.write(String.format("%s%18s%11s%20s\n", data.getId() , data.getIncome(), data.getMembers(),
                        data.getState()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM