Java中向文件追加数据的正确方法

Java中向文件追加数据的正确方法,java,file-io,append,filewriter,printwriter,Java,File Io,Append,Filewriter,Printwriter,对于这段代码,我想模拟一台老虎机,将游戏的用户名和分数放在一个名为scores.txt的文本文件中,这样,如果用户选择选项2,他们就可以查看自己的分数 然而,我在FileWriter语句行的末尾收到许多错误,并用注释标记,特别是我不理解的一个错误,称为编码CP1252的不可映射字符。从我检查过的每一个地方,当有人使用不同的字符(比如日语字符)时,我都会看到这个错误——那么为什么会出现这样的错误呢?我已经看过一些代码示例,但还没有学习过stream、try-and-catch或buffer 使用f

对于这段代码,我想模拟一台老虎机,将游戏的用户名和分数放在一个名为scores.txt的文本文件中,这样,如果用户选择选项2,他们就可以查看自己的分数

然而,我在FileWriter语句行的末尾收到许多错误,并用注释标记,特别是我不理解的一个错误,称为编码CP1252的不可映射字符。从我检查过的每一个地方,当有人使用不同的字符(比如日语字符)时,我都会看到这个错误——那么为什么会出现这样的错误呢?我已经看过一些代码示例,但还没有学习过stream、try-and-catch或buffer

使用filewriter和printwriter,有人可以向我解释如何创建filewriter对象并将其正确传递给printwriter对象,以及如何正确读取该文件scores.txt中的数据。提前非常感谢,如果这是一个简单的错误,请道歉

具体问题领域:

File file = new File(“scores.txt”); //illegal start of expression

    if (!file.exists())
    {
        file.createNewFile();
    }

    Scanner inputFile = new Scanner(file);
    String line = inputReader.nextLine();
    FileWriter fwriter = new FileWriter(“scores.txt”, true); //this is where the error CP1252, 
    PrintWriter outputWriter = new PrintWriter(file);
    outputFile.println(username);
    outputFile.println(userFinalTotal);

}

else if (option == 2)
{
    if (file.exists())
    {   
        while (inputFile.hasNext())
        {
            username = inputFile.nextLine();
            System.out.println ("Name\n------\n" + name + "\n");
            userFinaltotal = inputFile.nextDouble();
            System.out.printf("Scores\n------\n$%.2f\n", userFinalTotal);
            System.out.println();  
            inputReader.close();
        }
下面是查看变量来源的完整程序

import java.util.Scanner;
import java.util.Random;
import java.io.*;

public class SlotsMachine
{
public static void main(String[] args) throws IOException
{
    int number;

    System.out.println ("Welcome to the Slot Machine Simulator!");
    System.out.println ("\nActions\n1. Start a new game\n2. Scores\n3. Exit");
    System.out.print ("\nPlease select an action: ");

    Scanner keyboard = new Scanner(System.in);
    int option = keyboard.nextInt();

    while (option != 1 && option != 2 && option != 3)
    {
    System.out.print ("\nThat is not an option. Please select an item number between 1-3: ");
    option = keyboard.nextInt();
    break;
    }

    if (option == 1)
    {
        String username; 
        double startingTotal = 100.0;
        double userTotal = startingTotal;

        System.out.print ("\nBefore the game begins, please enter your name: ");
        username = keyboard.next( );
        System.out.print ("\nGame start! You will begin with $100.00. Enter a negative value to quit the game. Good luck, " + username + "!");

        do
        {
            double bet = keyboard.nextDouble();
            bet = 0.0;
            userTotal = startingTotal - bet;

            System.out.print ("You currently have: " + startingTotal + "\nHow much would you like to bet?");

            double winnings = 0.0;
            double userFinalTotal = 0.0;

            if ((bet < 0) || (userFinalTotal <= 0))
            {
                break;
            }

            while (bet > userFinalTotal)
            {
                System.out.print("\nYour bet is greater than your current total. Please enter a valid amount: ");
                bet = keyboard.nextDouble();
            }

            Random generator = new Random();
            int slot1 = generator.nextInt(6);
            keyboard.nextLine();

            int slot2 = generator.nextInt(6);

            int slot3 = generator.nextInt(6);

            String firstSlot = "";

            switch (slot1)
            {
                case 0:
                    firstSlot = "Cherries";
                    break;
                case 1:
                    firstSlot = "Oranges";
                    break;
                case 2:
                    firstSlot = "Plums";
                    break;
                case 3:
                    firstSlot = "Bells";
                    break;
                case 4:
                    firstSlot = "Melons";
                    break;
                case 5:
                    firstSlot = "Bars";
                    break;
            }

            String secondSlot = "";

            switch (slot2)
            {
                case 0:
                    secondSlot = "Cherries";
                    break;
                case 1:
                    secondSlot = "Oranges";
                    break;
                case 2:
                    secondSlot = "Plums";
                    break;
                case 3:
                    secondSlot = "Bells";
                    break;
                case 4:
                    secondSlot = "Melons";
                    break;
                case 5:
                    secondSlot = "Bars";
                    break;
            }

            String thirdSlot = "";

            switch (slot3)
            {
                case 0:
                    thirdSlot = "Cherries";
                    break;
                case 1:
                    thirdSlot = "Oranges";
                    break;
                case 2:
                    thirdSlot = "Plums";
                    break;
                case 3:
                    thirdSlot = "Bells";
                    break;
                case 4:
                    thirdSlot = "Melons";
                    break;
                case 5:
                    thirdSlot = "Bars";
                    break;
            }

            System.out.println ("-------------------------------");
            System.out.println ("" + firstSlot + "    " + secondSlot + "    " + thirdSlot);
            System.out.print ("-------------------------------");

            if (slot1 == slot2 && slot1 == slot3)
            {
                winnings = bet * 3;
                userFinalTotal = userTotal + winnings;
                System.out.printf ("\nNumber of matches: 3. You win: $%.2f", winnings); 
                System.out.printf ("\nYou currently have: $%.2f", userFinalTotal);
            }
            else if ((slot1 == slot2 && slot2 != slot3) || (slot1 == slot3 && slot1 != slot2) || (slot2 == slot3 && slot3 != slot1))
            {   
                winnings = bet * 2;
                userFinalTotal = userTotal + winnings;
                System.out.printf ("\nNumber of matches: 2. You win: $%.2f", winnings);
                System.out.printf ("\nYou currently have: $%.2fn", userFinalTotal);
            }   
            else
            {
                System.out.printf ("\nNumber of matches: 0. You win: $%.2f", winnings);
                System.out.printf ("\nYou currently have: $%.2f", userFinalTotal);
            }       
        } while (userTotal > 0);

        File file = new File(“scores.txt”); //illegal start of expression

        if (!file.exists())
        {
            file.createNewFile();
        }

        Scanner inputFile = new Scanner(file);
        String line = inputReader.nextLine();
        FileWriter fwriter = new FileWriter(“scores.txt”, true); //this is where the error CP1252
        PrintWriter outputWriter = new PrintWriter(file);
        outputFile.println(username);
        outputFile.println(userFinalTotal);

    }

    else if (option == 2)
    {
        if (file.exists())
        {   
            while (inputFile.hasNext())
            {
                username = inputFile.nextLine();
                System.out.println ("Name\n------\n" + name + "\n");
                userFinaltotal = inputFile.nextDouble();
                System.out.printf("Scores\n------\n$%.2f\n", userFinalTotal);
                System.out.println();  
                inputReader.close();
            }
        }
        else
        {   
            System.out.println("There are no scores to display at this time.");
        }

        System.out.println("Actions:");
        System.out.print("1. Start a new game\n2. View scores\n3. Exit ");

        System.out.println("Please select an action: "); 
        option = keyboard.nextInt();
    }

    else if (number == 3)
    {
        System.out.print ("\nGoodbye!");
        System.exit(0);
    } 
}

}

它现在可以编译了,唯一的问题是它会多次打印分数。 导入java.util.Scanner; 导入java.util.Random; 导入java.io.*

public class Slot3
{
public static void main(String[] args) throws IOException
{
    System.out.println ("Welcome to the Slot Machine Simulator!");

    int option = 0;

    //if the user selects a 1 or 2 (does not want to exit) then this loop will run
    do
    {
        System.out.println ("\nActions\n1. Start a new game\n2. Scores\n3. Exit");
        System.out.print ("\nPlease select an action: ");

        Scanner keyboard = new Scanner(System.in);
        option = keyboard.nextInt();
        keyboard.nextLine();

        while (option != 1 && option != 2 && option != 3)
        {
            System.out.print ("\nThat is not an option. Please select an item number between 1-3: ");
            option = keyboard.nextInt();
            keyboard.nextLine();
        }

        //this will occur if the user selects 1 to play the game
        if (option == 1)
        {
            double money = 100.00;
            double bet = 0.00;
            double winnings = 0.00;
            double score = 0.00;
            int count = 0;

            System.out.print ("\nBefore the game begins, please enter your name: ");
            String username = keyboard.nextLine();

            System.out.print ("\nGame start! You will begin with $100.00. Enter a negative value to quit the game. Good luck, " + username + "!");

            System.out.printf("\nYou currently have $%.2f.", 100.00);

            do 
            {
                System.out.printf("\n\nHow much would you like to bet? ");
                bet = keyboard.nextDouble();

                if ((bet < 0) || (money <= 0))
                {
                    break;
                }

                while (bet > money)
                {
                    System.out.print("\nYour bet is greater than your current total. Please enter a valid amount: ");
                    bet = keyboard.nextDouble();
                }

                //create random numbers
                Random generator = new Random();
                int slot1 = generator.nextInt(6);

                int slot2 = generator.nextInt(6);

                int slot3 = generator.nextInt(6);

                String firstSlot = "";

                switch (slot1)
                {
                    case 0:
                        firstSlot = "Cherries";
                        break;
                    case 1:
                        firstSlot = "Oranges";
                        break;
                    case 2:
                        firstSlot = "Plums";
                        break;
                    case 3:
                        firstSlot = "Bells";
                        break;
                    case 4:
                        firstSlot = "Melons";
                        break;
                    case 5:
                        firstSlot = "Bars";
                        break;
                }

                String secondSlot = "";

                switch (slot2)
                {
                    case 0:
                        secondSlot = "Cherries";
                        break;
                    case 1:
                        secondSlot = "Oranges";
                        break;
                    case 2:
                        secondSlot = "Plums";
                        break;
                    case 3:
                        secondSlot = "Bells";
                        break;
                    case 4:
                        secondSlot = "Melons";
                        break;
                    case 5:
                        secondSlot = "Bars";
                        break;
                }

                String thirdSlot = "";

                switch (slot3)
                {
                    case 0:
                        thirdSlot = "Cherries";
                        break;
                    case 1:
                        thirdSlot = "Oranges";
                        break;
                    case 2:
                        thirdSlot = "Plums";
                        break;
                    case 3:
                        thirdSlot = "Bells";
                        break;
                    case 4:
                        thirdSlot = "Melons";
                        break;
                    case 5:
                        thirdSlot = "Bars";
                        break;
                }

                System.out.println ("\n-------------------------------");
                System.out.printf ("%-12s%-10s%5s\n", firstSlot , secondSlot , thirdSlot);
                System.out.print ("\n-------------------------------");

                //check how many of the slots match to calculate the winnings
                if (slot1 == slot2 && slot1 == slot3)
                {
                    winnings = bet * 3;
                    money -= bet;
                    score = money + winnings;
                    System.out.printf ("\nNumber of matches: 3. You win: $%.2f", winnings); 
                     System.out.printf("\nYou currently have: $%.2f", score);
                }
                else if ((slot1 == slot2 && slot2 != slot3) || (slot1 == slot3 && slot1 != slot2) || (slot2 == slot3 && slot3 != slot1))
                {   
                    winnings = bet * 2;
                    money -= bet;
                    score = money + winnings;
                    System.out.printf ("\nNumber of matches: 2. You win: $%.2f", winnings);
                    System.out.printf("\nYou currently have: $%.2f", score);
                }   
                else
                {
                    winnings = bet * 0;
                    money -= bet;
                    score = money + winnings;
                    System.out.printf ("\nNumber of matches: 0. You win: $%.2f", winnings);
                    System.out.printf("\nYou currently have: $%.2f", score);
                }     
            } while ((bet > 0) && (money > 0)); 

            FileWriter fwriter = new FileWriter("scores.txt", true);
            PrintWriter outputWriter = new PrintWriter(fwriter);
            outputWriter.printf("\n\n%1s%15s" , "Name" , "Score");
            outputWriter.printf ("\n\n%1s%15s" , "----" , "-----");
            outputWriter.printf ("\n\n%1s%15s" , username , score);
            outputWriter.close();

            System.out.println("\n\nGame over! Your score has been written to scores.txt, " + username + "!");

        } //end of actions for select option 1

        //option 2 user wants to read their scores
        if (option == 2)
        {
            File myFile = new File("scores.txt");

            //if there are no scores to read
            if (!myFile.exists())
            {   
                System.out.println("There are no scores to display at this time.");
                continue;
            }

            File file = new File("scores.txt");

            Scanner inputFile = new Scanner(file);

            while (inputFile.hasNext())
            {
                String username = inputFile.nextLine(); 

                System.out.println(username);
            }
            inputFile.close();
        } //close option 2
    } while (option != 3); //close 1st do-while loop

    if (option == 3)
    {
        System.out.print ("\nGoodbye!");
        System.exit(0);
    } 
}

}

您遇到了什么错误?请尝试解决-大多数人不会费力地通过这么长的代码来找到大海捞针。如果您已经隔离了您的问题,您将能够更好地表达您的问题所在,因此帮助您将更加容易。@Vucar Timnärakrul因为它包含代码中的内容,所以我希望包含代码,以便您可以看到如果出现错误,需要包含哪些变量。我在有错误的行旁边放了一条注释,说明了错误:编码CP1252的不可映射字符,以及表达式的非法开始,并说我需要一个;我的朋友在哪里。从现在起,我将尝试在顶部添加特定的代码部分,感谢您的支持input@HedonicHedgehog我收到一个编码CP1252错误的不可映射字符,从我在线阅读的内容来看,当有人使用不同的字符(如日语字符)时,似乎会发生这种错误。我不知道怎么会这样。而且,在那条线上有一个错误,说应该有一个;其中逗号无效,并且表达式的开头非法。这行代码上有注释。你复制了那个文件名吗?看起来您使用的是java编译器不喜欢的定向引号。替换为无方向的