Solved

Java BufferedWriter, Printwriter help

Posted on 2011-02-20
17
461 Views
Last Modified: 2012-05-11
Hi,
I would like to have some help with this code. I want to be able to save customer data in a file and then show the result. The code works as long as I only write one customer.. but I want to be able to save several customers before I print the result.

I need the help right away! :)
package test;

import java.io.*;
import javax.swing.*;
import static javax.swing.JOptionPane.*;

public class Main {
  public static void main(String[] arg) throws IOException {
    PrintWriter outputStream = new PrintWriter
                         (new BufferedWriter
                         (new FileWriter("customers.txt", true)));
    while(true) {
      String name = JOptionPane.showInputDialog
                     ("The Customers name: ");
      
         
      
      if (name == null)
        break;
     
      String category = JOptionPane.showInputDialog
                      ("Customer Category (Business or Private): ");
      
      String discount = JOptionPane.showInputDialog
                      ("Discount: ");
      
      outputStream.println(name);
      outputStream.println(category);
      outputStream.println(discount);
      
      showMessageDialog(null, "The result: " + name + " " + category + " " + discount);
    }       
    outputStream.close();
    
  }      
}

Open in new window

0
Comment
Question by:Asimo
  • 10
  • 6
17 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 34938725
The code is fine although i'd do
if (name == null || (name = name.trim()).length() < 1) {
				break;
			}

Open in new window

0
 

Author Comment

by:Asimo
ID: 34938740
But I want to save several customers before I get to the result.. right now the result shows up after I have saved  one customer?

what is the difference with your code?
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34938741

DOnt' know but your code did not compile for me - this one I tried - it works

package test;

import java.io.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.JOptionPane.*;

public class Main extends Frame {
    public Main() {

        try {
        PrintWriter outputStream = new PrintWriter
                              (new BufferedWriter
                              (new FileWriter("customers.txt", true)));
            String savedCustomers = "";
         while(true) {
           String name = JOptionPane.showInputDialog
                          ("The Customers name: ");



           if (name == null || name.trim().length() == 0)
             break;

           String category = JOptionPane.showInputDialog
                           ("Customer Category (Business or Private): ");

           String discount = JOptionPane.showInputDialog
                           ("Discount: ");

           outputStream.println(name);
           outputStream.println(category);
           outputStream.println(discount);
                                       savedCustomers += " " +name + " ";
         }
          //   showMessage("The result: " + name + " " + category + " " + discount);
           JDialog d = new JDialog(this,  "Saved coutomers: " + savedCustomers);
             JLabel lbl = new JLabel(  "Saved customers: " + savedCustomers);
             d.add(lbl);
             d.setSize(300,300);
             d.show();

         outputStream.close();
        }catch(Exception ex){
            System.out.println("error " + ex.toString());
            ex.printStackTrace();
        }

    }


  public static void main(String[] arg) throws IOException {
                          new Main();

   //     showMessage("The result: " + name + " " + category + " " + discount);
   //   JDialog d = new JDialog(this, true, "The result: " + name + " " + category + " " + discount);

  }


}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 34938747
Yes in the code which I posted it will save several, and then show the names of those saved
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34938755
It will finish and show result when you enter a customer with empty name
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34938778
This is the same thing but shows mssage window rather than
JDialog - that's why it didn't compile originally - there
was no JOptionPane befor showMeassageDialog

Anyway I also moved your code out of main method -
it is not a good practice


package test;

import java.io.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.JOptionPane.*;

public class Main extends Frame {
    public Main() {

        try {
        PrintWriter outputStream = new PrintWriter
                              (new BufferedWriter
                              (new FileWriter("customers.txt", true)));
            String savedCustomers = "";
         while(true) {
           String name = JOptionPane.showInputDialog
                          ("The Customers name: ");



           if (name == null || name.trim().length() == 0)
             break;

           String category = JOptionPane.showInputDialog
                           ("Customer Category (Business or Private): ");

           String discount = JOptionPane.showInputDialog
                           ("Discount: ");

           outputStream.println(name);
           outputStream.println(category);
           outputStream.println(discount);
                                       savedCustomers += " " +name + " ";
         }
          //   showMessage("The result: " + name + " " + category + " " + discount);

            JOptionPane.showMessageDialog(null, "Saved coutomers: " + savedCustomers);
              /*
           JDialog d = new JDialog(this,  "Saved coutomers: " + savedCustomers);
             JLabel lbl = new JLabel(  "Saved customers: " + savedCustomers);
             d.add(lbl);
             d.setSize(300,300);
             d.show();
            */
         outputStream.close();
        }catch(Exception ex){
            System.out.println("error " + ex.toString());
            ex.printStackTrace();
        }

    }


  public static void main(String[] arg) throws IOException {
                          new Main();

   //     showMessage("The result: " + name + " " + category + " " + discount);
   //   JDialog d = new JDialog(this, true, "The result: " + name + " " + category + " " + discount);

  }


}

Open in new window

0
 

Author Comment

by:Asimo
ID: 34938799
for yan> Your code works. But it is a bit to advanced for me since I am still a beginner.. I am supposed to use dialogboxes and then show the result in a dialog box. :-( So even if it works I can not use it.. and even if I could I can´t explan it.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34938823
I made both variants - first with Dialog, which I guedss you are not suppose to use - the second one is with JOptionPane - you can remove all stuff relted too dialog from that varoiant - it is commeneted out and is not needed
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 47

Expert Comment

by:for_yan
ID: 34938867
Remove all lines between the /* and */ symbols and also the lines which are commented out by two slashes // in the second variant of code - and you'll not see any trace of dialog
0
 

Author Comment

by:Asimo
ID: 34938894
Right! Sorry missed that.. but the result box doesn´t show all the information. Just the names.. I have to get everything in the result box. Name, category and discount...
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34938910
Well you can add it as it was befire, but if you want to accumulaste for all of them add it to the string savedCustomer whoich is being acuumulated throur the loop. Try to do it, if it does not work, I'll help you in an hour when I get back to my computer
0
 
LVL 47

Accepted Solution

by:
for_yan earned 250 total points
ID: 34939035
That is with the rest of information

package test;

import java.io.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.JOptionPane.*;

public class Main extends Frame {
    public Main() {

        try {
        PrintWriter outputStream = new PrintWriter
                              (new BufferedWriter
                              (new FileWriter("customers.txt", true)));
            String savedCustomers = "";
         while(true) {
           String name = JOptionPane.showInputDialog
                          ("The Customers name: ");



           if (name == null || name.trim().length() == 0)
             break;

           String category = JOptionPane.showInputDialog
                           ("Customer Category (Business or Private): ");

           String discount = JOptionPane.showInputDialog
                           ("Discount: ");

           outputStream.println(name);
           outputStream.println(category);
           outputStream.println(discount);
                                       savedCustomers += " " +name + " " + category + " " + discount + " ";
         }
          //   showMessage("The result: " + name + " " + category + " " + discount);

            JOptionPane.showMessageDialog(null, "Results: " + savedCustomers);
              /*
           JDialog d = new JDialog(this,  "Saved coutomers: " + savedCustomers);
             JLabel lbl = new JLabel(  "Saved customers: " + savedCustomers);
             d.add(lbl);
             d.setSize(300,300);
             d.show();
            */
         outputStream.close();
        }catch(Exception ex){
            System.out.println("error " + ex.toString());
            ex.printStackTrace();
        }

    }


  public static void main(String[] arg) throws IOException {
                          new Main();

   //     showMessage("The result: " + name + " " + category + " " + discount);
   //   JDialog d = new JDialog(this, true, "The result: " + name + " " + category + " " + discount);

  }


}

Open in new window

0
 

Author Comment

by:Asimo
ID: 34939162
Thanks! I changed it a little.. :)

I have some questions and I hope you can help me with them. Why is the main method in the buttom? and why is the code this?

"public class Main extends Frame {
    public Main() "
package test;

import java.io.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.JOptionPane.*;

public class Main extends Frame {
    
    public Main() {

        try {
        PrintWriter outputStream = new PrintWriter
                              (new BufferedWriter
                              (new FileWriter("customers.txt", true)));
             
        String savedCustomers = "";

                
         while(true) {
           String name = JOptionPane.showInputDialog
                          ("The Customers name: ");


           if (name == null || name.trim().length() == 0)
             break;

           String category = JOptionPane.showInputDialog
                           ("Customer Category (Business or Private): ");

           String discount = JOptionPane.showInputDialog
                           ("Discount: ");

           outputStream.println(name);
           outputStream.println(category);
           outputStream.println(discount);
                                     
           savedCustomers += "Customer: " + name + "\n" + "Category: " + category + "\n" + "Discount: " + discount + " %" + "\n" + "\n";
           
          } 
           JOptionPane.showMessageDialog(null, "Customer Information: " + "\n" + "\n" + savedCustomers);


         outputStream.close();
         
        }catch(Exception ex){
            System.out.println("error " + ex.toString());
            ex.printStackTrace();
        }

    }


  public static void main(String[] arg) throws IOException {
                          new Main();
    
  }

}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 34939179
I believ you can remove "extends Frame" - it will still work - I neede it for Dialog
with JOptionPane you don't need it.

It does not matter where the methods are placed in a class - it will always start with method main()

You name the calss Main - even thow Java is case sensitive and upper case letter
allows to distingusih it from method main - it is a bad practice to do so - better name
calsses with what they are doing - say MyWriter  

The first line public class Main ... is a class declaration and opening line

the next line piblic Main() - is the openeing of specuial method - constructor
of the class which always shoul be named as the class but has parenthezes as oposed to class openeing line

 

 
0
 

Author Comment

by:Asimo
ID: 34939340
I thought I could. :) And I tried to move main etc.. and it worked but it was awesome to get an explanation from you.  

Thanks a lot for your help!
0
 

Author Closing Comment

by:Asimo
ID: 34939350
Perfect explanation!
0
 
LVL 47

Expert Comment

by:for_yan
ID: 34939408
You are welcome
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
get weblogic logged in user in java 2 59
Java JRE greater than 1.6 5 51
servlet  URL Rewriting 1 28
difference of if loops 23 43
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now