文件处理的问题



我是一个新手java程序员,我有麻烦的文件输出与我的java项目。在这个项目中,我应该有一个"石头,布,剪刀"程序,将输出结果到一个单独的文件。当我运行程序然后查看文件时,它只记录最近的结果,而不是所有的结果。如果有什么建议就太好了。请原谅我的失礼;我稍后会打扫的。我也删除了大部分的评论,以便缩短它。谢谢。

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);
            }
        }
}

当您执行decideOutcome()时,每次都要重新打开一个PrintStream文件。

但是这个构造函数并不查找到文件的末尾!这意味着您每次都要覆盖内容。

尝试使用FileWriter代替,使用适当的构造函数。

编辑:由于分配似乎要求您使用PrintStream(为什么?),您将不得不这样做:
PrintStream output = new PrintStream(new FileOutputStream("records.txt", true));

但在现实生活中,您可能会使用BufferedWriter;几乎没有人使用PrintStream

您正在使用的Printstream从开头开始写入文件,而不是从最后一行开始。使用Filewriter处理文件会更好,因为它有附加和插入模式。您需要的是追加模式。

您永远不能使用PrintStream以您正在做的方式完成此任务。API明确指出PrintStream的构造函数执行以下操作:

PrintStream(文件文件)使用指定的文件创建新的打印流,但不自动刷新行。

file -要用作打印流目的地的文件。如果文件存在,那么它将被截断为零大小;否则,将创建一个新文件。输出将被写入文件并被缓冲。

没有允许你追加到前一个文件的构造函数。

因此,解决方案在于您只能使用一次PrintStream构造函数。这可以通过使output变量成为一个类变量并去掉decideOutcome()中的声明(以及try-catch)来实现。
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();
  }
}

另一件需要注意的重要事情是,无论何时打开一个流(如Scanner或PrintStream),都应该关闭它。关闭它们的最佳位置是在finally子句中,因为这部分代码可以保证运行。

相关内容

  • 没有找到相关文章

最新更新