2013-09-30 2 views
0

전화 청구서를 계산하고이 형식으로 콘솔에 출력하도록 자바 파일을 설정했습니다.동일한 형식의 콘솔 출력을 텍스트 문서로 인쇄 할 수 없습니다.

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

하지만이 프로그램을 실행할 때 나는 단지

Account Amount_Due 
10011 $12.25 
10033 $11.7 

누군가가 나에게 올바른 형식으로 내 filecreating 코드를 편집 도와 드릴까요 텍스트 파일에이 얻을?

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

    } 
} 
+0

'System.out'에 쓰는 모든 것을'out' 문자열에 추가하지 말고'String' 대신'StringBuilder'를 사용해야합니다. – A4L

+0

인쇄 중이며 쓰여진 문자열에 추가 중입니다. 두 사람은 같은 장소에 가지 않습니다. –

답변

0

연구하십시오. 그것은 좀 더 고급 Java를 사용하지만 이해하는 것은 당신의 가치가있을 것입니다.

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

    } 
} 
+0

와우. 나는 당신의 수정 된 코드를 실행하고 elementexceptions을 얻었다. – DarkD

+0

nvm이 그것을 알아 냈다. 당신의 고마워요! – DarkD

+0

ElementException? 그게 뭐야? 스택 추적을 보여줄 수 있습니까? – UFL1138

0

콘솔 (예 : System.out.println)에 인쇄하는 것은 out 변수 (예 : + =)를 연결하는 것과 동일하지 않습니다.

그래서 당신은 당신 만 파일에 문자열 '밖'에서 무엇을 작성하는

writeToFile("invoice.txt", out); 

를 호출 할 때. 코드를 살펴보면 누락 된 행은 모두 콘솔에만 인쇄되지만 'out'변수에는 연결되지 않는다는 것을 알 수 있습니다. 그것을 정정하면 문제가 없어야합니다.

+0

무슨 뜻인지 알 겠어. 이 문제를 해결할 수있는 방법을 제안 해 주시겠습니까? – DarkD

+0

예. 귀하의'processCharges()'메소드에서. 'System.out.println ("some string")'줄을 사용할 때마다 찾아라. 각 라인 바로 다음에'out + = "과 같은 라인을 추가하십시오. –

+0

오오오 지금 받으십시오. THankls – DarkD

관련 문제