How to specify which file to write to?

2019-09-20 08:18发布

问题:

I'm creating a program that takes the users input of currentSales, and if it's less than 1000 it goes to lowPerformer or more than 1000 goes to highPerformer.txt file. I'm stuck at the if statement. I'm not sure how I would code the program to tell the data what file to save to. Any assistance is appreciated.

public class HighandLowSales {
   public static void main(String[] args) {
      Scanner input1 = new Scanner(System.in);
      Path highPerformer =
              Paths.get("C:\\Users\\C\\Desktop\\IS103 "
                      + "Programming Logic\\Week7\\HighSales.txt");
      Path lowPerformer = 
              Paths.get("C:\\Users\\C\\Desktop\\IS103 Programming Logic\\"
                      + "Week7\\LowSales.txt");
      String delimiter = ",";
      String s;
      int id;
      String firstName;
      String lastName;

      double currentSales;
      final int QUIT = 999;
      try {
         Scanner input = new Scanner(System.in);
         OutputStream output = 
            new BufferedOutputStream(Files.newOutputStream(highPerformer, CREATE));
         OutputStream output1 =
            new BufferedOutputStream(Files.newOutputStream(lowPerformer, CREATE));

         BufferedWriter writer = 
            new BufferedWriter(new OutputStreamWriter(output));
         BufferedWriter writer1 = 
            new BufferedWriter(new OutputStreamWriter(output1));

         System.out.print("Enter employee ID number >> ");
         id = input.nextInt();
         while(id != QUIT) {
            System.out.print("Enter first name for employee #" + 
                             id + " >> ");
            input.nextLine();
            firstName = input.nextLine();
            System.out.print("Enter last name for employee # " +
                             id + " >> ");
            input.nextLine();
            lastName = input.nextLine();
            System.out.print("Enter current month sales in whole dollar " +
                             "for employee #" + id + " >> ");
            input.nextLine();
            currentSales = input.nextDouble();
            s = id + delimiter + firstName + delimiter + lastName + delimiter
                            + currentSales;

            if (currentSales>1000) 
               writer.write(s);


            writer.newLine();
            writer1.newLine();
            System.out.print("Enter next ID number or " + QUIT +
                             "to quit");
            id = input.nextInt();
         }
         writer.close();

      } catch(Exception e) {
         System.out.println("Message: " + e);
      }          
   }          
}

回答1:

if(currentSales>1000){
    //write to high performer file
    writer.write(s);
} else {
    //write to low performer file
    writer1.write(s);
}