2013-05-13 146 views
0

我想寫一個程序,用戶可以選擇將數據寫入文件或讀取文件。寫入或從文件讀取

我不知道爲什麼我的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 2013-05-13 21:24:13

+1

如果結構不能正常工作,「if-else」是什麼意思?請解釋.. – Smit 2013-05-13 21:27:02

+0

提示:使用''V「.equalsIgnoreCase(choice)'而不是'choose.equalsIgnoreCase(」V「)'來消除'NullPointerException'的可能性。 – 2013-05-13 21:29:33

回答

5

因爲您否則,如果被關閉

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

刪除分號;

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

發現這個你發佈它的第二個!好時機:) +1 – christopher 2013-05-13 21:33:43

+2

好眼睛。正在尋找這樣的東西,但看不到它。 +1 – 2013-05-13 21:35:51

+0

克里斯感謝您將我的時間節約至無限......! – user2379362 2013-05-13 21:39:32