写入或从文件读取
我想写一个程序,用户可以选择将数据写入文件或读取文件。写入或从文件读取
我不知道为什么我的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!");
}
}
}
因为您否则,如果被关闭
else if (choice.equalsIgnoreCase("A"));
删除分号;
else if (choice.equalsIgnoreCase("A"))
发现这个你发布它的第二个!好时机:) +1 – christopher 2013-05-13 21:33:43
好眼睛。正在寻找这样的东西,但看不到它。 +1 – 2013-05-13 21:35:51
克里斯感谢您将我的时间节约至无限......! – user2379362 2013-05-13 21:39:32
您是否试过在调试器中单步执行代码? – Blorgbeard 2013-05-13 21:24:13
如果结构不能正常工作,“if-else”是什么意思?请解释.. – Smit 2013-05-13 21:27:02
提示:使用''V“.equalsIgnoreCase(choice)'而不是'choose.equalsIgnoreCase(”V“)'来消除'NullPointerException'的可能性。 – 2013-05-13 21:29:33