【发布时间】: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,完美地说明了这个问题。当然,术语并不准确,但您只需运行提供的代码即可查看问题。