【问题标题】:Writing to OR Reading from a file [closed]写入或读取文件[关闭]
【发布时间】:2013-05-13 21:20:26
【问题描述】:

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

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

        }
    }
}

【问题讨论】:

  • 您是否尝试过在调试器中单步执行代码?
  • if-else if structure is not working correctly 是什么意思?请解释..
  • 提示:使用"V".equalsIgnoreCase(choice) 而不是choice.equalsIgnoreCase("V") 以消除NullPointerException 的可能性。
  • 不确定问题出在哪里。 OP 发布了一个 SSCCE,完美地说明了这个问题。当然,术语并不准确,但您只需运行提供的代码即可查看问题。

标签: java bluej


【解决方案1】:

因为你的 else if 已关闭

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

去掉分号;

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

【讨论】:

  • 在你发布它的第二秒就发现了这个!好时机:) +1
  • 好眼光。正在寻找类似的东西,但看不到它。 +1
  • 克里斯感谢你为我节省了无穷无尽的时间......!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-09
  • 2010-09-22
  • 1970-01-01
  • 1970-01-01
  • 2013-05-29
相关资源
最近更新 更多