2013-05-13 5 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

+1

'구조가 제대로 작동하지 않는다면'if-else '란 무엇을 의미합니까? 설명해주세요. – Smit

+0

팁 :'NullPointerException' 가능성을 없애기 위해'choose.equalsIgnoreCase ("V")'대신' "V".equalsIgnoreCase (choice)'를 사용하십시오. –

답변

5

당신의 다른 때문에 닫혀 있으면

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

제거 세미콜론 ;

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

두 번째로 게시했습니다. 좋은 타이밍 :) +1 – christopher

+2

좋은 눈. 이 같은 것을 찾고 있었지만 그것을 볼 수 없었습니다. +1 –

+0

무한대로 시간을 절약 해 주신 크리스 감사합니다 ...! – user2379362

관련 문제