2012-02-06 1 views
0

저는 학교 프로젝트의 초기 단계에 있으며 이미 버그가 있습니다. While 루프를 사용하지 않고 for 루프를 사용하여 배열 목록 내용을 내보내는 경우 모든 항목이 올바르게 작동하지만 while 루프를 사용하여 옵션을 제공 할 수있는 경우 출력 텍스트 파일에 프로그램이 단순히 포함되어 있지 않은 것처럼 아무것도하지 않고 빈 텍스트 파일을 만듭니다. 나 엄청 혼란스러워.while 루프를 추가 한 후 Printwriter가 지정된 파일로 출력되지 않는 것 같습니다.

import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.PrintWriter; 
import java.util.ArrayList; 
import java.util.Scanner; 
import java.io.PrintStream; 
import javax.swing.JOptionPane; 
import java.util.Arrays; 

public class studentProcessor 
{ 
    public static void main(String[] args) throws FileNotFoundException 
    { 
     PrintStream pr=System.out; 
     String inputFileName = JOptionPane.showInputDialog("Input file:"); 
     String outputFileName = JOptionPane.showInputDialog("Output file:"); 
     File inputFile = new File(inputFileName); 
     Scanner in = new Scanner(inputFile); 
     PrintWriter out = new PrintWriter(outputFileName); 
     ArrayList<Student>student = new ArrayList<Student>(); 
     while (in.hasNextLine()) 
     { 
      student.add(new Student(in.nextInt(), in.next(), in.nextDouble())); 
     } 
     in.close(); 
     boolean done=false; 
     while (!done) 
     { 
      String m=JOptionPane.showInputDialog("Please enter the number for the action which you would like to perform." + 
       "\n1. Add new student(s)\n2. Remove student(s)\n3. Update student's data\n4. Search for student" + 
       "\n5. Sort students\n6. Create GPA report\n7. Output information to a .txt file\n0. Exit"); 
      if (m.equals("1")) 
      { 
       JOptionPane.showMessageDialog(null, "Add new student(s)"); 
      } 
      else if (m.equals("2")) 
      { 
       JOptionPane.showMessageDialog(null, "Remove student(s)"); 
      } 
      else if (m.equals("3")) 
      { 
       JOptionPane.showMessageDialog(null, "Update student's data"); 
      } 
      else if (m.equals("4")) 
      { 
       JOptionPane.showMessageDialog(null, "Search for a student"); 
      } 
      else if (m.equals("5")) 
      { 
       JOptionPane.showMessageDialog(null, "Sort students"); 
      } 
      else if (m.equals("6")) 
      { 
       JOptionPane.showMessageDialog(null, "Create GPA report"); 
      } 
      else if (m.equals("7")) 
      { 
       JOptionPane.showMessageDialog(null, "Output information to a .txt file"); 
       out.println("The students' information is listed below:"); 
       for (Student Stu:student) 
       { 
        out.println(Stu.getId()+" "+Stu.getLName()+" "+Stu.getGpa()); 
       } 
      } 
      else if (m.equals("0")) 
      { 
       System.exit(0); 
       done=true; 
      } 
      else 
      { 
       JOptionPane.showMessageDialog(null, "You have not entered a valid command, try again."); 
      } 
     } 
     out.close(); 
    } 
} 

여기에 제가 사용하는 학생 수업이 있습니다. 어떤 도움

class Student 
{ 
private int id; 
private String lName; 
private double gpa; 

public Student (int studentId, String studentLName, double studentGpa) 
    { 
    id=studentId; 
    lName=studentLName; 
    gpa=studentGpa; 
    } 

public int getId() 
    { return id; } 

public String getLName() 
    { return lName; } 

public double getGpa() 
    { return gpa; } 

public void setId(int id) 
    { this.id=id; } 

public void setLName(String lName) 
    { this.lName=lName; } 

public void setGpa(double gpa) 
    { this.gpa=gpa; } 

} 

감사 =]

편집 :이 지금의 PrintWriter와 함께 작동 코드의 새로운 섹션입니다. 모든 도움을 주셔서 감사합니다!

else if (m.equals("7")) 
     { 
      String outputFileName = JOptionPane.showInputDialog("Designate an output file for student information:"); 
      PrintWriter out = new PrintWriter(outputFileName); 
      out.println("The students are listed below:"); 
      for (Student Stu:student) 
      { 
       out.println(Stu.getId()+" "+Stu.getLName()+" "+Stu.getGpa()); 
      } 
      out.close(); 
     } 
+0

왜 System.exit (0)을 가지고 있습니까? done을 false로 설정하면 프로그램이 종료되고 outfile을 적절하게 닫을 수 있습니다. –

답변

1

당신은 그것을 작성 후 출력 스트림을 플러시해야 사용자가 쓰기 옵션 (7)을 선택하면

out.flush(); 

또한, 당신이 당신의 출력 스트림을 생성 할 것입니다. 그렇지 않으면 레코드를 동일한 파일에 반복해서 쓰게됩니다. 그래서 좀 더 비슷해 :

 } else if (m.equals("7")) { 
     JOptionPane.showMessageDialog(null, 
       "Output information to a .txt file"); 
     final PrintWriter out = new PrintWriter(outputFileName); 
     out.println("The students' information is listed below:"); 
     for (Student Stu : student) { 
      out.println(Stu.getId() + " " + Stu.getLName() + " " 
       + Stu.getGpa()); 
     } 
     out.close(); 
    } 
+0

또 다른 답변에서 내 의견을 계속하려면, 나는 당신이 보여준 위치로 out.close()를 옮겼다. idk 그것이 전적으로 out.close를 배치 한 경우이거나 out 파일에 대한 문자열의 초기화를 이동했기 때문에 idk입니다. 내가 무엇을했는지에 대한 편집을 게시 할 것입니다. –

+0

PrintWriter가 코드 실행 방식에 큰 변화를주기 전에 '최종'을 묻는 질문을하고 싶습니다. 미안하지만, 나는 초보자이며,이 프로그램에 대한 첫 번째 시도입니다. –

+0

final을 사용하여 변수에 태그를 지정하면 컴파일러에서 특정 종류의 최적화를 수행 할 수 있기 때문에 프로그램을 향상시킬 수 있습니다. 당신이 그것을 밖으로 떠나는 경우에 살인자가 아니다. – Perception

1

PrintWriter를 닫기 전에 플러시()를 시도 했습니까?

+0

클로저를 사용하면 작성기가 플러시되고 close 메서드가 호출되지 않는 것이 문제입니다. –

+0

실제로 맞습니다 - 나는 그 불쾌한 System.exit()를 보지 못했습니다. –

2

문제는 out.close가있는 행이 절대로 호출되지 않는다는 것입니다.

인쇄 작성기를 닫기 전에 System.exit 메서드가 응용 프로그램을 종료합니다.

리소스를 닫으려면 try finally 블록을 사용해야합니다.

System.exit 호출이 while 루프가 아닌 메서드의 끝 부분에 있으면 코드가 더 명확 해집니다. 루프를 종료하려면 이미 부울을 사용하고 있으므로 종료하고 나머지 코드를 계속 진행하십시오.

+0

system.exit()을 지적 해 주셔서 고마워요. 내가 부울로 바꾼 후에 그것을 삭제하는 것을 잊어 버렸습니다. 또한 내 문제를 알아 내고 루프 내에서 출력 파일의 문자열을 정확히 초기화 할 때 프로그램 시작 부분에서 대신 사용하고 싶습니다. –