Я пытаюсь написать программу, в которой пользователь имеет возможность записывать данные в файл или читать файл.Запись в OR Чтение из файла
Я не знаю, почему моя структура 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!");
}
}
}
Вы пробовали переходить через код в отладчике? – Blorgbeard
Что вы подразумеваете под 'if-else, если структура работает некорректно'? Пожалуйста, объясните .. – Smit
Совет: используйте '' V ".equalsIgnoreCase (выбор)' вместо 'choice.equalsIgnoreCase (" V ")', чтобы исключить возможность «NullPointerException». –