简体   繁体   English

将输出循环到Java中的.txt文件

[英]Looping an output to a .txt file in Java

So here's my code: 所以这是我的代码:

import java.io.*;
import java.util.*;

public class Main {
public static void main(String[] args){

    ArrayList<Employee> ArrEmployee = new ArrayList<Employee>(); //  array for employee objects

        try {
            Scanner txtIn = new Scanner(new File("payroll.txt"));
            PrintWriter txtOut = new PrintWriter("payrollError.txt");


            while (txtIn.hasNext()) { // looping through the payroll.txt file and creating Employee objects from its data
                try{
                long EmployeeNumber = txtIn.nextLong();
                String EmployeeName = txtIn.next();
                String LastName = txtIn.next();
                double HoursWorked = txtIn.nextDouble();
                double HourlyWage = txtIn.nextDouble();
                if (HourlyWage > 10.35){ 
                    throw new InputMismatchException(); // throws exception if the hourly wage is less than 10.35$
                }
                else
                    ArrEmployee.add(new Employee(EmployeeNumber,EmployeeName,LastName,HoursWorked,HourlyWage)); // creates Employee objects according to the input payroll.txt
                }
                catch (InputMismatchException n) { // catching long,strings and doubles in the payroll.txt that aren't valid
                    txtOut.println(Employee.EmployeeNumber + " " + Employee.EmployeeName + " " + Employee.LastName + " " + Employee.HoursWorked + " " + Employee.HourlyWage);
                    System.out.println("lol");
                      }
                txtOut.close();
            }

        } catch (FileNotFoundException e) {
            System.out.println("File payroll.txt was not found.");

            }

          }

        }

I'm trying to output to a .txt file called payrollError.txt but for some reason, the while loop goes on infinitely... 我正在尝试输出到一个名为payrollError.txt的.txt文件,但是由于某种原因,while循环会无限进行...

I can't seem to find the problem in my main class and any help would be appreciated. 我似乎在我的主班上找不到问题,将不胜感激。

Here's my code from the payroll.txt : 这是来自payroll.txt的代码:

31718 PHILLIP LENNOX 55.0 20.00
11528 NANCY TROOPER 40.0 10.45
16783 JOHN CONNAUGHT 30.5 10.00
10538 PETER DUNCAN 45.0 10.75
21O15 JAMES HAROLD 32.0 10.50
61326 HARRY KUHN 25.0 12.30
82465 MICHELLE BENOIT 50.0 18.50
31816 DANIELLE RAYMOND 35.5 15.25
73745 JACK O'TOOLE 28.0 11.50
81514 VICTORIA HALL 48.5 17.50
71854 ALI MOHUMAD 35.0 10.75
92012 ALLAN MARS 36.0 15.00
52853 MICHAEL BOONE 60.5 17.50
41714 JULIE HART 25.0 10.50
58342 MIKE HEINZ 28.2 16.85
62080 PIETRO SULA 32.5 11.50
21638 MICHEL RAE 40.5 12.50
52726 MITCHELL HACKETT 23,7 12.05

Basically it's supposed to loop through these (long,string,string,double,double) like by line, find any values that are invalid like a double written as 23,7 instead of 23.7 and output it to my file payrollError.txt. 基本上应该按行循环遍历这些(long,string,string,double,double),找到无效的任何值,例如写为23,7而不是23.7的double并将其输出到我的文件payrollError.txt。

My Employee class: 我的员工班:

public class Employee {

     public static long EmployeeNumber;
     public static String EmployeeName;
     public static String LastName;
     public static double HoursWorked;
     public static double HourlyWage;

    public Employee(long EmployeeNumber, String EmployeeName, String LastName, double HoursWorked, double HourlyWage ){

        this.EmployeeNumber = EmployeeNumber;
        this.EmployeeName = EmployeeName;
        this.LastName = LastName;
        this.HoursWorked = HoursWorked;
        this.HourlyWage = HourlyWage;
    }
}

Don't close the output in your while loop body. 不要在while循环主体中关闭输出。 Also, please follow Java variable naming conventions. 另外,请遵循Java变量命名约定。 Instead of displaying "lol" try and output the message you're writing. 不要显示“大声笑”,而是尝试输出您正在编写的消息。 If you can't initialize the Employee it's hard to see how your existing method could get the values that were read. 如果您无法初始化Employee则很难看到现有方法如何获取读取的值。 Finally, you need to close() your PrintWriter (or use a try-with-resources as below to do it for you). 最后,您需要close() PrintWriter (或使用如下的try-with-resources为您完成此操作)。 Something like 就像是

List<Employee> al = new ArrayList<>();
try (PrintWriter txtOut = new PrintWriter("payrollError.txt")) {
    Scanner txtIn = new Scanner(new File("payroll.txt"));
    while (txtIn.hasNext()) {
        long employeeNumber;
        String employeeName;
        String lastName;
        double hoursWorked;
        double hourlyWage;

        try {
            employeeNumber = txtIn.nextLong();
            employeeName = txtIn.next();
            lastName = txtIn.next();
            hoursWorked = txtIn.nextDouble();
            hourlyWage = txtIn.nextDouble();
            if (hourlyWage > 10.35) {
                throw new InputMismatchException();
            } else {
                al.add(new Employee(employeeNumber, employeeName,
                                lastName, hoursWorked, hourlyWage));
            }
        } catch (InputMismatchException n) {
            String msg = employeeNumber + " " + employeeName + " "
                    + lastName + " " + hoursWorked + " " + hourlyWage;
            txtOut.println(msg);
            System.out.println(msg);
        }
        // txtOut.close(); // <-- this is inside the loop.
    }
} catch (FileNotFoundException e) {
    System.out.println("File payroll.txt was not found.");
}

Your fields cannot be static in your Employee class! 您的字段不能在Employee类中是static (And I would make them lowercase to follow Java naming conventions; otherwise they look like class names) (而且我会让它们小写以遵循Java命名约定;否则它们看起来像类名)

 private /* static */ long EmployeeNumber;
 private /* static */ String EmployeeName;
 private /* static */ String LastName;
 private /* static */ double HoursWorked;
 private /* static */ double HourlyWage;

Making the fields private is an example of encapsulation. 将字段设为private是封装的一个示例。

Better to use buffered reader and writer when using file streams . 使用文件流时最好使用缓冲的读写器。

modifying your code using those: 使用以下命令修改您的代码:

public class Main {
    public static void main(String[] args) {
        ArrayList<Employee> ArrEmployee = new ArrayList<Employee>();
        FileReader bfr = null;
        try {
            bfr = new FileReader(new File("payroll.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        BufferedReader br = new BufferedReader(bfr);
        String EmployeeName = "no data";
        FileWriter bfw = null;
        try {
            bfw = new FileWriter("payroolError.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
        BufferedWriter txtOut = new BufferedWriter(bfw);

    try {
        while (br.read() != -1) {
            String temp = br.readLine();
            Pattern p = Pattern.compile(" ");
            String[] items = p.split(temp);
            try {
                int EmployeeNumber = Integer.parseInt(items[0]);
                EmployeeName = items[1];
                String LastName = items[2];
                double HoursWorked = Double.parseDouble(items[3]);
                double HourlyWage = Double.parseDouble(items[4]);
                if (HourlyWage > 10.35) {
                    throw new InputMismatchException();
                } else {
                    ArrEmployee
                            .add(new Employee(EmployeeNumber, EmployeeName,
                                    LastName, HoursWorked, HourlyWage));
                }
            } catch (NumberFormatException n) {
                txtOut.write(EmployeeName);
            } catch (InputMismatchException n) {
                txtOut.write(EmployeeName);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM