添加 while 循环后,Printwriter 似乎没有输出到指定文件

发布于 2025-01-02 18:34:10 字数 4100 浏览 0 评论 0原文

我正处于学校项目的早期阶段,并且已经遇到了一个错误。如果我只是使用 for 循环导出数组列表内容而不使用 while 循环,则一切正常,但是当我想使用 while 循环以便可以提供选项时,输出文本文件不包含任何内容,就好像程序只是除了创建一个空文本文件之外什么也没做。我很困惑。

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();
        }

I am in the early stages of a project for school and have already run into a bug. If I simply export the array list contents using the for loop without the while loop everything works fine, but when I want to use the while loop so that I can provide options, the output text file doesn't contain anything as if the program simply didn't do anything but create an empty text file. I am very confused.

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();
   }
}

and here is the Student class I am using.

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; }

}

thanks for any help =]

EDIT: this is the new section of the code that works with printwriter now. thanks for all the help!

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();
        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

撧情箌佬 2025-01-09 18:34:10

问题是带有 out.close 的行永远不会被调用。

System.exit 方法在关闭打印编写器之前终止您的应用程序。

您应该使用 try finally 块来关闭资源。

此外,如果 System.exit 调用位于方法末尾而不是在 while 循环中,您的代码会更清晰。您已经使用布尔值来终止循环,因此让它终止,然后继续执行其余代码。

The problem is that the line with out.close is never being called.

The System.exit method terminates your application before closing the print writer.

You should use a try finally block for closing your resources.

Also your code would be clearer if the System.exit call was at the end of the method instead of in the while loop. You're already using a boolean to terminate the loop, so let it terminate, and continue to the rest of your code.

長街聽風 2025-01-09 18:34:10

您需要在写入后刷新输出流:

out.flush();

此外,您将需要在用户选择写入选项 (7) 时创建输出流。否则您将重复将记录写入同一个文件。所以更像这样:

     } 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();
     } 

You need to flush your output stream after writing to it:

out.flush();

In addition, you will want to create your output stream when the user selects your write option (7). Otherwise you will write the records to the same file repeatedly. So something more like this:

     } 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();
     } 
月下伊人醉 2025-01-09 18:34:10

您是否在关闭 PrintWriter 之前尝试过对其进行刷新()?

Have you tried flush()ing the PrintWriter before closing it?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文