gpt4 book ai didi

Java文件输入

转载 作者:行者123 更新时间:2023-12-01 13:47:45 25 4
gpt4 key购买 nike

我目前正在新职位中完成一项任务。基本上我需要做的是从文件中获取数字并将它们相乘。我的文件内容如下

Dave

7 35

Lucy

6 19

我需要获取每个人的数字并将它们相乘,以便稍后使用它们,到目前为止我已经有了这段代码,我确信有一个更简单的方法,因为这看起来很冗长。打印到屏幕只是为了测试它是否有效。

import java.util.*; 
import java.io.*;
import javax.swing.JOptionPane;
public class Task1
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner inFile = new Scanner(new FileReader("ExternalData.txt"));
String name;
double rate;
double hours;
name = inFile.next ();
rate = inFile.nextDouble();
hours = inFile.nextDouble();
double weeklypay1 = rate * hours;
String name2;
double rate2;
double hours2;
name2 = inFile.next ();
rate2 = inFile.nextDouble();
hours2 = inFile.nextDouble();
double weeklypay2 = rate * hours;

System.out.println("Daves pay:" + weeklypay2);

}
}

我的问题基本上是这看起来像是一个很好的布局方式还是我完全错误的方式,对于java来说非常陌生,所以希望得到任何帮助,提前致谢!

最佳答案

这是清理此问题的快速尝试:

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Task1 {
@SuppressWarnings("resource")
public static void main(String[] args) throws FileNotFoundException {
Scanner inFile = new Scanner(new FileReader("ExternalData.txt"));
List<Employee> employees = new ArrayList<>();
while(inFile.hasNext()) {
employees.add(new Employee(inFile.next(), inFile.nextDouble(), inFile.nextDouble()));
}
for(Employee employee : employees) {
System.out.println(employee);
}
}
}

使用此类(保存员工数据并干净地打印它):

public class Employee {
public final String name;
public final double rate;
public final double hours;
public final double weeklypay;

public Employee(String name, double rate, double hours) {
this.name = name;
this.rate = rate;
this.hours = hours;
this.weeklypay = this.rate*this.hours;
}

public String toString() {
return name+"'s pay:" + weeklypay;
}
}

使用您的文本文件,它会生成以下输出:

Dave's pay:245.0
Lucy's pay:114.0

或者您可以将它们存储在 Map 中(以名称作为键)并执行如下操作:

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Task1 {
@SuppressWarnings("resource")
public static void main(String[] args) throws FileNotFoundException {
Scanner inFile = new Scanner(new FileReader("/ExternalData.txt"));
Map<String, Employee> employees = new HashMap<>();
while(inFile.hasNext()) {
Employee employee = new Employee(inFile.next(), inFile.nextDouble(), inFile.nextDouble());
employees.put(employee.name, employee);
}
System.out.println(employees.get("Dave"));
}
}

关于Java文件输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20224469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com