Search code examples
javafilefilewriter

Unable to print console output in same format onto text document


I have my java file set up to calculate a phone bill and print out to the console in this format.

Invoice
--------------------------
Account   Amount Due 
10011      $12.25
10033      $11.70
--------------------------
Total      $23.95

but when I run the program I only get this on the text file

Account Amount_Due
10011 $12.25
10033 $11.7

Can someone help me edit my filecreating code in correct format?

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.Vector;


public class PhoneBill {
    Vector data;
    Vector processed = new Vector();

    Vector markProcessed = new Vector();
    public void readFile(String inFileStr)
    {
        String str = "";
        data = new Vector<LineItem>();
        FileReader fReader;
        InputStream inFileStream;
         try{
        fReader = new FileReader(inFileStr);
            BufferedReader br=new BufferedReader(fReader);
            String line;
            while ((line=br.readLine())!= null){
                if (line.indexOf("_") != -1)
                    continue;
                else
                  if (!line.isEmpty()){
                    data.add(new LineItem(line.trim()));

                  }
            }

            br.close(); 
        }       
        catch (Exception e){

        }
    }
    public void processCharges()
    {
        String out = "Account Amount_Due\n";
        System.out.println ("Invoice");
        System.out.println ("--------------------------");
        System.out.println ("Account   " + "Amount Due ");
        double total = 0.0;
        double lCharges =0;
        boolean done = false;
        DecimalFormat numFormatter = new DecimalFormat("$##.##");
        for (int j = 0; j < data.size(); j++ ){
            LineItem li =  (LineItem)data.get(j);
            String accNum = li.getAccountNum();
            if (j > 0){
                done = checkProcessed(accNum);}
            else
                processed.add(accNum);
            if (!done){
                   lCharges = 0;
            for (int i = 0; i < data.size(); i++){
              String acc = ((LineItem)data.get(i)).getAccountNum();
              if (acc.equals(accNum) && !done)
              lCharges += processItemCharges(accNum);
              done = checkProcessed(accNum);
            }
            lCharges+=10.0;
            System.out.format ("%s" + "      $%.2f%n",accNum, lCharges);
            out += accNum+" ";
            out += numFormatter.format(lCharges)+"\n";
            processed.add(accNum);

             total += lCharges;
            }

        }

        System.out.println ("--------------------------");
        System.out.format ("%s" + "      $%.2f%n","Total", total);
        writeToFile("invoice.txt", out);

    }
    private void writeToFile(String filename,String outStr)
    {
        try{
            File file = new File(filename);

            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(outStr);
            bw.close();

        } catch (IOException ioe){
            System.out.println(ioe.getMessage());
        }

    }
    private boolean checkProcessed(String accNum){
        if (processed.contains(accNum))
            return true;
        else
            return false;
    }


    private double processItemCharges(String accNum)
    {
        double charges = 0.0;

        for (int i = 0; i < data.size(); i++)
        {
            if(((LineItem)data.get(i)).getAccountNum().equals(accNum))
                charges += ((LineItem)data.get(i)).getCharges();
        }
        return charges;
    }
    public static void main(String[] args)
    {
        PhoneBill pB =  new PhoneBill();
        pB.readFile("input_data.txt");
        pB.processCharges();
    }

    class LineItem{
        String accNum ;
        String timeOfCall;
        double mins;
        double amountDue;
        boolean counted = false;

        public LineItem(String accStr)
        {
            processAccount(accStr);
        }

        private void processAccount(String accStr){
            StringTokenizer st = new StringTokenizer(accStr);
            accNum = (String)st.nextElement();
            timeOfCall = (String) st.nextElement();
            mins = Double.parseDouble((String) st.nextElement());
            if (timeOfCall.compareTo("08:00")>0 && timeOfCall.compareTo("22:00")<0)
                amountDue = mins*0.10;
            else
                amountDue = mins*0.05;
        }

        public String getAccountNum()
        {
            return accNum;
        }

        public double getCharges()
        {
            return amountDue;
        }

    }
}

Solution

  • Study this. It uses a bit more advanced Java but understanding it will be well worth your while.

    package test;
    
    import java.io.*;
    import java.util.*;
    
    public class PhoneBill {
    
        private static String BILL_FORMAT = "%-10s $%,6.2f\n";
        private static boolean DEBUG=true;
    
        Map<String, List<LineItem>> accounts = new HashMap<String,List<LineItem>>();
    
        public void readFile(String inFileStr) {
            FileReader fReader=null;
            try {
                fReader = new FileReader(inFileStr);
                BufferedReader br = new BufferedReader(fReader);
                String line;
                while ((line = br.readLine()) != null) {
                    if (line.indexOf("_") != -1)
                        continue;
                    else if (!line.isEmpty()) {
                        LineItem li = new LineItem(line.trim());
                        List<LineItem> list = accounts.get(li.accNum);
                        if(list==null){
                            list = new ArrayList<LineItem>();
                            accounts.put(li.accNum, list);
                        }
                        list.add(li);
                    }
                }
    
                br.close();
            } catch (Exception e) {
                /* Don't just swallow Exceptions. */
                e.printStackTrace();
            } finally { 
                if(fReader!=null){
                    try{
                        fReader.close();
                    } catch(Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
    
        public void processCharges() {
            StringBuffer out = new StringBuffer(100)
                .append("Invoice\n")
                .append("--------------------------\n")
                .append("Account   Amount Due \n");
            double total = 0.0;
            double lCharges = 0;
    
            for (String accNum:accounts.keySet()) {
                List<LineItem> account = accounts.get(accNum);
                lCharges = 10;
                for(LineItem li:account){
                    lCharges += li.getCharges();
                }
                total += lCharges;
                out.append(String.format(BILL_FORMAT, accNum, lCharges));
            }
    
            out.append("--------------------------\n");
            out.append(String.format(BILL_FORMAT, "Total", total));
            writeToFile("invoice.txt", out.toString());
    
        }
    
        private void writeToFile(String filename, String outStr) {
            if(DEBUG){
                System.out.printf("========%swriteToFile:%s=========\n", '=', filename);
                System.out.println(outStr);
                System.out.printf("========%swriteToFile:%s=========\n", '/', filename);
            }
            try {
                File file = new File(filename);
    
                // If file doesn't exist, then create it.
                if (!file.exists()) {
                    file.createNewFile();
                }
    
                FileWriter fw = new FileWriter(file.getAbsoluteFile());
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write(outStr);
                bw.close();
    
            } catch (IOException ioe) {
                System.out.println(ioe.getMessage());
            }
    
        }
    
        public static void main(String[] args) {
            PhoneBill pB = new PhoneBill();
            pB.readFile("input_data.txt");
            pB.processCharges();
        }
    
        static class LineItem {
            String accNum;
            double timeOfCall;
            double mins;
            double amountDue;
            boolean counted = false;
    
            private static final double EIGHT_AM = convertTime("08:00");
            private static final double TEN_PM = convertTime("22:00");
    
            public LineItem(String accStr) {
                processAccount(accStr);
            }
    
            private void processAccount(String accStr) {
                StringTokenizer st = new StringTokenizer(accStr);
                accNum = st.nextToken();
                timeOfCall = convertTime(st.nextToken());
                mins = Double.parseDouble(st.nextToken());
                if (timeOfCall > EIGHT_AM && timeOfCall < TEN_PM)
                    amountDue = mins * 0.10;
                else
                    amountDue = mins * 0.05;
            }
    
            public String getAccountNum() {
                return accNum;
            }
    
            public double getCharges() {
                return amountDue;
            }
    
            private static double convertTime(String in){
                /* Will blow up if `in` isn't given in h:m. */
                String[] h_m = in.split(":");
                return Double.parseDouble(h_m[0])*60+Double.parseDouble(h_m[1]);
            }
    
        }
    }