我有点卡在这里。目前我正在为学校做一个项目。我最近发现代码应该从文件读取而不是从用户输入读取。有什么方法可以改变我的过程吗?我需要它读取的文件是QuarterlyEmployeeData.txt 这是我的主要课程:
MonthlyPayroll.java
import java.util.*;
class MonthlyPayrollDriver
{
private static final int WORKFORCE_SIZE = 3;
private static Scanner inputScan;
public static void main (String[] args)
{
// Set up array of employees
// Note the objects in the array could be in subclasses of Employee
Employee[] employeeList = new Employee[WORKFORCE_SIZE];
inputScan = new Scanner(System.in);
for(int empNum = 0; empNum < WORKFORCE_SIZE; empNum++)
{
System.out.print("Enter employee first name and last name: ");
String first = inputScan.next();
String last = inputScan.next();
System.out.print("\nPlease determind the Status code (F for full-time, P for part time, and I for intern) ");
char response = inputScan.next().charAt(0);
{
if (response == 'f' || response == 'F')
{
System.out.print("\nPlease determind the Status Code (S for salaried or H for hourly) ");
{
char response1 = inputScan.next().charAt(0);
if (response1 == 'h' || response1 == 'H')
{
System.out.print("\nEnter hourly rate: ");
double hourlyRate = inputScan.nextDouble();
System.out.print("\nEnter hours worked last Month: ");
inputScan.nextDouble();
employeeList[empNum] = new HourlyEmployee(last,first,hourlyRate);
}
char response2 = inputScan.next().charAt(0);
if (response2 == 's' || response2 == 'S')
{
System.out.print("Enter annual salary: ");
double annualPay = inputScan.nextDouble();
employeeList[empNum] = new SalariedEmployee(last,first,annualPay);
}
}
}
if (response == 'p' || response == 'P')
{
System.out.print("\nEnter hourly rate: ");
double hourlyRate = inputScan.nextDouble();
System.out.print("\nEnter hours worked last month: ");
inputScan.nextDouble();
employeeList[empNum] = new HourlyEmployee(last, first,
hourlyRate);
}
if (response == 'i' || response == 'I')
{
System.out.print("\nPlease determind the Status Code (H for hourly or U for unpaid.) ");
{
char response1 = inputScan.next().charAt(0);
if (response1 == 'H' || response1 == 'h')
{
System.out.print("\nEnter hourly rate: ");
double hourlyRate = inputScan.nextDouble();
System.out.print("\nEnter hours worked last month: ");
inputScan.nextDouble();
employeeList[empNum] = new HourlyEmployee(last, first,
hourlyRate);
}
else
{
employeeList[empNum] = new HourlyEmployee(last,first,0);
}
}
}
}
}
System.out.println("\n\nMonthly Payroll\n");
for(int j = 0; j < WORKFORCE_SIZE; j++)
{
System.out.println(employeeList[j]);
}
}
}
答案 0 :(得分:2)
当然,改变
inputScan = new Scanner(System.in);
到
inputScan = new Scanner(new File(filePath));
其中filePath
是您需要阅读的File
的路径。 Scanner(File)
javadoc说,
构造一个新的
Scanner
,用于生成从指定文件扫描的值。
答案 1 :(得分:1)
这是使您的程序从标准输入读取的原因,默认情况下是控制台:
inputScan = new Scanner(System.in);
您可以通过两种方式更改此内容:
第一个选项是这样完成的:
java MonthlyPayrollDriver <my_input_file.txt
第二个选项是这样完成的:
File file = new File("my_input_file.txt");
inputScan = new Scanner(file);