2013-05-13 1 views
0

Я пытаюсь написать программу, в которой пользователь имеет возможность записывать данные в файл или читать файл.Запись в 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!"); 

     } 
    } 
} 
+0

Вы пробовали переходить через код в отладчике? – Blorgbeard

+1

Что вы подразумеваете под 'if-else, если структура работает некорректно'? Пожалуйста, объясните .. – Smit

+0

Совет: используйте '' V ".equalsIgnoreCase (выбор)' вместо 'choice.equalsIgnoreCase (" V ")', чтобы исключить возможность «NullPointerException». –

ответ

5

Потому что ваш еще, если закрыт

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

удалить точку с запятой ;

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

Пятнистый это второй вы отправили его! Хорошее время :) +1 – christopher

+2

Хороший глаз. Смотрел что-то вроде этого, но не мог его увидеть. +1 –

+0

Крис благодарит меня за то, что сэкономил мне часы до бесконечности ...! – user2379362