Pregunta

I'm a novice java programmer and I am having trouble with file output with my java project. In this project, I'm supposed to have a "Rock, Paper, Scissors" program which will output the results onto a separate file. When I run the program and then look at the file, it only records the most recent result instead of every one. Any advice on what to do would be great. Please excuse the poor form; I will clean it up later. I've also erased most of the comments in order to shorten it. Thanks.

import java.util.*;
import java.awt.*;
import java.io.*;


public class RockPaperScissors {


    public static int count = 0;

    public static void main(String[] args) {

            execute(); 
    }


    public static void execute(){       

        System.out.println("This program will allow you to play \n\"Rock, Paper, Scissors\" against a computer.");
        System.out.println();
        System.out.println("Enter 'r' for Rock, 'p' for Paper, or s for Scissors.");
        System.out.println("Enter 'w' to have an insta-win for that round. Enter '-1' at anytime to exit program.");

        String info = userInput();
        int value = guessCode();
        decideOutcome(value, info);
        again();
        }


        public static String userInput() {
        Scanner console = new Scanner (System.in);  
        String s = console.next();
        return s;
    }

        public static int guessCode() {
        Random r = new Random ();   
        return (r.nextInt(3)+1); // Random integer between 1 and 3;
    }

    public static void decideOutcome(int i, String j) {

        try {
            PrintStream output = new PrintStream(new File ("records.txt"));

            if (j.equalsIgnoreCase("rock")|| j.equalsIgnoreCase("r")) {
                count++;
                switch (i){
                    case 1:
                        System.out.println("You've won! Computer picked scissors.");
                        output.println(count + " Win ");
                        break;
                    case 2:
                        System.out.println("You've tied.... Computer also picked rock.");
                        output.println(count + " Tie ");
                        break;
                    case 3:
                        System.out.println("You've lost. Computer picked paper.");
                        output.println(count + " Loss ");
                        break;
                    }           
            } else if (j.equalsIgnoreCase("paper")|| j.equalsIgnoreCase("p")) {
                count++;
                switch (i){
                    case 1:
                        System.out.println("You've lost; Computer picked scissors.");
                        output.println(count + " Loss ");
                        break;
                    case 2:
                        System.out.println("You've won! Computer picked rock.");
                        output.println(count + " Win ");
                        break;
                    case 3:
                        System.out.println("You've tied.... Computer also picked paper.");
                        output.println(count + " Tie ");
                        break;
                    }
            } else if (j.equalsIgnoreCase("scissors")|| j.equalsIgnoreCase("s")) {
                count++;
                switch (i){
                    case 1:
                        System.out.println("You've tied.... Computer picked scissors.");
                        output.println(count + " Tie ");
                        break;
                    case 2:
                        System.out.println("You've lost; Computer picked rock.");
                        output.println(count + " Loss ");
                        break;
                    case 3:
                        System.out.println("You've won! Computer also picked paper.");
                        output.println(count + " Win ");
                        break;
                    }
            } else if (j.equalsIgnoreCase("w")) {
                count++;
                System.out.println("You've effortlessly defeated the computer!");
                output.println(count + " Win ");
            } else if (j.equals("-1")) {
                System.out.println("Thanks for playing!"); // need to find way to reach end.

                if (count == 1) { // If the user terminates after the first match.
                    System.out.println("You've played a single match.");        
                } else if (count > 1) { // Anything more than 1 match played upon termination.
                    System.out.println("You've played " + count + " matches total.");   
                } else { // This is for exceptions when user inputs gibberish for their sign and then 'no' for the second input.
                    System.out.println("No matches were played.");  
            }           
                System.out.println("Good Bye!");
                System.exit(0);
            } else {
                System.out.println("You didn't input the right thing.");
            }
        } catch (FileNotFoundException e) {
                System.out.println("File was not found; try again");
        }
    }

    public static void again() {
            System.out.println("Do you want to play again? (Type in 'y' for Yes or 'n' for No.)");

            Scanner console2 = new Scanner (System.in);

            String t = console2.next();

            while (t.equalsIgnoreCase("yes")||t.equalsIgnoreCase("y")) {
                System.out.println();
                System.out.println();
                execute(); // 
            }  
            if (t.equalsIgnoreCase("no") || t.equalsIgnoreCase("n") || t.equals("-1")) {
                System.out.println("Hope you had fun! I'm sure I've had just as much fun with making this program! Good Bye!");         

                if (count == 1) { // If the user terminates after the first match.
                        System.out.println("You've played a single match.");        
                } else if (count > 1) { // Anything more than 1 match played upon termination.
                        System.out.println("You've played " + count + " matches total.");   
                } else { // This is for exceptions when user inputs gibberish for their sign and then 'no' for the second input.
                        System.out.println("No matches were played.");              
                }   
                System.exit(0);

            } else { // If the user doesn't input 'yes' or 'no.'
                System.out.println("Not the proper response, but it's assumed that you don't want to continue.");   
                if (count == 1) { // If the user terminates after the first match.
                    System.out.println("You've completed a single match."); 
                } else if (count >= 2) { // Anything more than 1 match played upon termination.
                    System.out.println("You've completed " + count + " matches total.");
                } else { // The user haphazardly messes up both inputs.
                    System.out.println("No matches were finished.");
                }
                System.exit(0);
            }
        }
}
¿Fue útil?

Solución

When you decideOutcome(), you reopen a PrintStream to the file each time.

But this constructor does not seek to the end of the file! Which means you overwrite the contents each time.

Try using a FileWriter instead, with the appropriate constructor.

Edit: since the assignment seems to require that you use a PrintStream (why?), you will have to do this instead:

PrintStream output = new PrintStream(new FileOutputStream("records.txt", true));

But in real life, you will probably use a BufferedWriter instead; pretty much nobody uses PrintStream.

Otros consejos

The Printstream you are using starts writing to the file from the beginning and not from where the last line is. It will be better to use Filewriter to work on files as it has append and insert modes. What you need is the append mode.

You can never use a PrintStream to accomplish this task in the way you are doing it. The API clearly states that the constructor of the PrintStream does the following:

PrintStream(File file) Creates a new print stream, without automatic line flushing, with the specified file.

file - The file to use as the destination of this print stream. If the file exists, then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.

There are no constructors that allow you to append to the previous file.

The solution therefore lies in the fact that you can only use the PrintStream constructor exactly ONCE. This can be achieved by making your output variable a class variable and getting rid of your declaration (as well as the try-catch) in decideOutcome().

private static PrintStream output;

public static void main(String[] args) {
  try {
    output = new PrintStream(new File("records.txt"));
    execute();
  } catch (FileNotFoundException e) {
    System.out.println("File was not found; try again");
  } finally {
    output.close();
  }
}

Another important thing to note is that whenevre you open a stream such as a Scanner or a PrintStream you should always close it. The best place to close them is in a finally clause as that part of your code is guaranteed to run.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top