2014-04-27 3 views
0

J'ai des variables qui sont de ma main, et je veux utiliser une méthode privée (ou publique n'a pas vraiment d'importance, je les garde dans la même classe) pour les écrire dans un fichier texte. J'ai accompli les écrire dans un fichier à partir de la principale ... Je ne peux pas comprendre comment appeler les variables du principal dans ma méthode writeToFile(). Ci-dessous est ce que j'ai essayé, mais je ne sais pas comment intégrer les deux.Écrire dans un fichier à partir d'une méthode avec des variables de Main

//This portion is what I had in my main method that wrote the info to a file successfully 

    //Write to File 
      String fileName = "order.txt"; 
      try{ 
       PrintWriter writer = new PrintWriter(fileName); 
       writer.println("Thank you for ordering from Diamond Cards"); 
       writer.println("Name: " + customerName); 
       writer.println("Returning Customer: " + customerReturn); 
       writer.println("Phone: " + custNumber); 
       writer.println("Card Type: " + customerType); 
       writer.println("Card Color: " + customerColor); 
       writer.println("Card Coating: " + customerCoat); 
       writer.println("Item Amount: " + numItems); 
       writer.println("Total Cost: " + fmt1.format(totalCostMsg)); 
       writer.flush(); 
       writer.close(); 
       JOptionPane.showMessageDialog(null, "Receipt has been printed"); 
      } catch (FileNotFoundException e) 
         {e.printStackTrace(); 
         System.exit(0) ;   
         }  
      } 


// This is where I try to create a method to do the file writing.... not sure how to proceed.. 


    public static void writeToFile() { 
      try{ 
       FileWriter fw = new FileWriter("order.text"); //File name to be created 
       PrintWriter pw = new PrintWriter (fw);   // Prints to the file that was created 
     //text to be printed to file 

     // close the writer  
       pw.close(); 
     // catch errors  
       } catch (IOException e) { 
       out.println("Error!"); 
       } 
      } 

Je dois aussi savoir comment faire une méthode distincte pour lire le fichier en arrière mais je pense que je peux concevoir que si je peux comprendre cette partie dehors.

+0

Ajoutez simplement les paramètres dont vous avez besoin dans 'writeToFile()' pour pouvoir les transmettre ... –

+0

en tant que tel? writeToFile (customerName, numItems, ..... blah)? – user3537993

Répondre

1

Vous souhaitez définir writeToFile avec des arguments, et les transmettre à partir main:

// Add additional arguments. 
    public static void writeToFile(String fileName, String customerName, ...){ 
     FileWriter fw = new FileWriter(fileName); 
     writer.println("Thank you for ordering from Diamond Cards"); 
      writer.println("Name: " + customerName); 
     // Use additional arguments. 
    } 

De principale:

writeToFile(fileName, customerName, ...); 

Je suis d'accord avec M. Polywhirl bien. Ce sera plus propre si vous créez un objet d'emballage, même si je ne suis pas sûr que vous avez besoin de getters et setters à cette fin.

// The types are all String because you did not mention the types in your 
// question. 
class Customer { 
    public String Name; 
    public String Return; 
    public String Number; 
    public String Type; 
    public String Color; 
    public String Coat; 
    public Customer String(String Name, String Return, String Number, String Type, String Color, String Coat) { 
     this.Name = Name; 
     this.Return = Return; 
     this.Number = Number; 
     this.Type = Type; 
     this.Color = Color; 
     this.Coat = Coat; 

    } 
} 

Vous pouvez ensuite effectuer les opérations suivantes dans main:

Customer c = new Customer(customerName, customerReturn, customerNumber, customerType, customerColor, customerCoat); 

Dans la méthode writeToFile avec la même signature que la réponse de M. Polywhirl, vous pouvez directement faire customer.Name, etc. Vous

1

peut passer des objets en ajoutant des paramètres à vos méthodes. Si vous avez besoin de référencer quelque chose dans une autre classe ou méthode, ajoutez simplement plus de paramètres.

Je vous suggère de créer un objet Client afin que vous puissiez le transmettre en tant qu'entité unique au lieu d'une douzaine de paramètres.

Vous pouvez essayer quelque chose comme ceci:

public class FileWriteExample { 
    public static void main(String[] args) { 
     String fileName = "order.txt"; 
     Customer customer; // Customer object... 
     int itemCount; 
     float totalCost; 
     try { 
      PrintWriter writer = new PrintWriter(fileName); 
      writeToFile(writer, customer, itemCount, totalCost); 
      writer.flush(); 
      writer.close(); 
      JOptionPane.showMessageDialog(null, "Receipt has been printed"); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
      System.exit(0); 
     } 
    } 
    public static void writeToFile(PrintWriter writer, Customer customer, 
      int itemCount, float totalCost) { 
     Card card = customer.getCard(); 
     try { 
      writer.println("Thank you for ordering from Diamond Cards"); 
      writer.println("Name: " + customer.getName()); 
      writer.println("Returning Customer: " + customer.getReturn()); 
      writer.println("Phone: " + customer.getPhone()); 
      writer.println("Card Type: " + card.getType()); 
      writer.println("Card Color: " + card.getColor()); 
      writer.println("Card Coating: " + card.getCoating()); 
      writer.println("Item Amount: " + itemCount); 
      writer.println("Total Cost: " + fmt1.format(totalCost)); 
     } catch (IOException e) { 
      System.out.println("Error!"); 
     } 
    } 
} 
0

Il pourrait y avoir des champs qui ne sont pas nécessaires ou indisponibles, comme numéro de téléphone, etc. Au lieu d'envoyer une longue liste pour écrire dans le fichier, pensez à utiliser un Builder Pattern comme suggéré par Joshua Bloch dans Java efficace.

Questions connexes