Solved

Java BufferedWriter, Printwriter help

Posted on 2011-02-20
17
456 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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

757 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

22 Experts available now in Live!

Get 1:1 Help Now