简体   繁体   English

保存到txt文件java

[英]Saving to txt file java

so I have my program working but the only problem is when the information is saved to the .txt file, there are no spaces eg the text file says "paul214" when it should say "paul 2 1 4", and does anyone know to stop the file over writing itself each time a new player plays the game? 所以我的程序可以工作,但是唯一的问题是信息保存到.txt文件时,没有空格,例如文本文件应显示“ paul 2 1 4”时显示“ paul214”,有人知道吗每次新玩家玩游戏时都停止文件覆盖自身吗?

import java.util.Random;
import java.util.Scanner;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

public class GuessingGame3 {

    public static void main(String[] args)
    {

        Random generator = new Random(); //This is were the computer selects the Target

        int guess;
        int count = 0;
        int Target;
        String userName;
        String playagain;
        boolean play = true;
        int session = 0;
        int sessions = 0;
        int lowestScore = 6;

        Scanner consoleIn = new Scanner(System.in); 
        Scanner name = new Scanner(System.in); 

        System.out.println("Hello! Please enter your name:\n"); 
        userName= name.nextLine();//This is were the user enters his/her name

        System.out.println("Hello "+ userName + " :) Welcome to the game!\n");


        while (play == true) //This is where the game starts up
        {
            session++; //This counts the number of goes the player has 
            Target = generator.nextInt(100) + 1;
            System.out.println("Can you guess the number i'm thinking off? You will have 6 attempts to guess the correct number"); //This is where the computer asks the user to guess the number and how many guesses they will have

            do {
                guess = consoleIn.nextInt();
                count++;

                if (guess > Target)
                System.out.println("Sorry! Your guess was too high! Guess again :)"); //This is to help the player get to the answer 
                else 
                if (guess < Target)
                System.out.println("Sorry! Your guess was too low! Guess again :)"); //This is to help the player get to the answer 
               }        
                while(guess != Target && count <6);

                if(guess == Target) {
                System.out.println("Congratulations "+  userName + ", it took you "+ count +" attempts to guess correctly!"); //This tells the player that they got the correct answer and how many attempts it took
                    sessions++;
                        }   
                else 
                {
                System.out.println("Sorry "+ userName + ", You've used up all of your guesses! The correct answer was "+ Target + "!");  //This tells the player that they failed to find the number and then tells them what the correct answer  
                }
                while ( count < lowestScore)
                {
                    lowestScore = count;
                }
                {
                Scanner answer = new Scanner(System.in);
                System.out.println("Would you like to play again "+ userName +"? [Y/N]");//This asks the player if they would like to play again
                playagain = answer.nextLine();
               if(playagain.equalsIgnoreCase("Y"))//This is what happens if the player opts to play again
                {
                play = true;
                count = 0;


                } else if(playagain.equalsIgnoreCase("N"))//This is what happens if the player opts to exit the game
                {
                    play = false;
                    System.out.println("Thanks for playing "+ userName +"! :) Please come back soon!");
            try {//This is where the program writes the information about the player to a .txt file 
                BufferedWriter writer =
                    new BufferedWriter ( new FileWriter(".\\Records.txt"));

                    writer.write(userName);

                    writer.write(String.valueOf(session));

                    writer.write(String.valueOf(sessions));

                    writer.write(String.valueOf(lowestScore));

                    writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
                    //This displays the information saved to the .txt file to the player. 
                    System.out.println("The number of goes you had: "+ session +"");
                    System.out.println("The number of times you guessed correctly: "+ sessions +"");
                    System.out.println("Your lowest score was: "+ lowestScore +"!");
                    break;
                }

             }
        }
    }
}       

You need to explicitly add spaces if you want them to be there: 如果需要空格,则需要显式添加空格:

writer.write(userName);
writer.write(" ");
writer.write(String.valueOf(session));
writer.write(" ");
writer.write(String.valueOf(sessions));
writer.write(" ");
writer.write(String.valueOf(lowestScore));

As for your second question you can append to the file like so: 至于第二个问题,您可以像这样附加到文件中:

BufferedWriter writer = new BufferedWriter ( new FileWriter(".\\Records.txt", true));
writer.append("your content");

The second parameter true sets the FileWriter to append mode. 第二个参数trueFileWriter设置为追加模式。

If you want spaces, you need to write spaces to the text file. 如果需要空格,则需要在文本文件中写入空格。 Example: 例:

writer.write(userName + " ");

If you don't want your text file overwritten, set append to true when you instantiate your FileWriter object: 如果不想覆盖文本文件,请在实例化FileWriter对象时将append设置为true:

new FileWriter(".\\\\Records.txt", true)

You can use \\t to create a tab in a file. 您可以使用\\t在文件中创建标签。

writer.write(userName+"\t");
................


  output = new BufferedWriter(new FileWriter(my_file_name, true));//you have to open the file in append mode

有谁知道每次新玩家玩游戏时都停止文件覆盖本身?

BufferedWriter writer = new BufferedWriter (new FileWriter(".\\\\Records.txt", true)); // true for appending a text to existing file

The reason there are no spaces is because you didn't specify to add them. 之所以没有空格,是因为您未指定添加空格。 The variables do not have a space at the end, so they do not write that way. 变量的末尾没有空格,因此它们不会这样写。 Do this instead: 改为这样做:

try {//This is where the program writes the information about the player to a .txt file 
    BufferedWriter writer = new BufferedWriter ( new FileWriter(".\\Records.txt"));

    writer.write(userName + " ");

    writer.write(String.valueOf(session) + " ");

    writer.write(String.valueOf(sessions) + " ");

    writer.write(String.valueOf(lowestScore));

    writer.close();
} catch (IOException e) {
    e.printStackTrace();
}

Or, you could write it using string concatenation: 或者,您可以使用字符串串联来编写它:

try {//This is where the program writes the information about the player to a .txt file 
    BufferedWriter writer = new BufferedWriter ( new FileWriter(".\\Records.txt"));
    writer.write(userName + " " + String.valueOf(session) + " " + String.valueOf(sessions) + " " + String.valueOf(lowestScore));
    writer.close();
} catch (IOException e) {
    e.printStackTrace();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM