写入或从文件中读取

时间:2013-05-13 21:20:26

标签: java bluej

我正在尝试编写一个程序,用户可以选择将数据写入文件或读取文件。

我不知道为什么我的if-else if结构不能正常工作。当我尝试查看数据时,程序会显示数据,然后在不应该输入时请求更多输入。

我会发布我希望有人可以帮助解决看似愚蠢而简单的问题。

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

public class Candy
{
    public static void main(String[] args)
    throws IOException
    {
        String candyname;
        String input="";

        //create scanner object
        Scanner keyboard=new Scanner(System.in);

        System.out.print("[V]iew or [A]ppend Database (V or A)?===>");
        String choice=keyboard.nextLine();

        if (choice.equalsIgnoreCase("V"))
        {
            //open the file
            File file=new File("candy");
            Scanner inputFile=new Scanner(file);

            //display the lines
            while (inputFile.hasNext())
            {
                //read a line
                candyname=inputFile.nextLine();

                //display a line
                System.out.println(candyname);
            }

            //close the file
            inputFile.close();

            System.out.println("\nComplete!");
        }

        else if (choice.equalsIgnoreCase("A"));
        {
            //open the file
            FileWriter fwriter=new FileWriter("candy", true);

            System.out.println("Type 'end' to STOP entering names\n");
            do
            {
                //get the name of the candy
                System.out.print("Enter the name of the candy===>");
                candyname=keyboard.nextLine();

                if (candyname.equalsIgnoreCase("end"))
                {
                    //break; //breaks out of loop
                    //or use a null if clause (empty)
                }
                else if (!(candyname.equalsIgnoreCase("end")))
                {
                    //append to file
                    PrintWriter outputFile=new PrintWriter(fwriter);
                    outputFile.println(candyname);
                }                

            }while (!(candyname.equalsIgnoreCase("end")));// || candyname !="END");

            //close the file
            fwriter.close();

            System.out.println("\nComplete!");

        }
    }
}

1 个答案:

答案 0 :(得分:5)

因为你的其他人已关闭

 else if (choice.equalsIgnoreCase("A"));

删除分号;

 else if (choice.equalsIgnoreCase("A"))