0

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

我不知道为什么我的 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!");

        }
    }
}
4

1 回答 1

5

因为你的 else if 已关闭

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

删除分号

 else if (choice.equalsIgnoreCase("A"))
于 2013-05-13T21:32:42.917 回答