Java 试图读入一个文件并获取同一行中的独立信息
我试图从这个文件中获取每一条单独的信息,将其分配给一个变量,使用数据创建一个Customer对象,然后将其添加到Customer对象数组中。这是一个项目,我必须使用数组,而不是ArrayList,我必须在readCustomerFile方法中使用2个扫描仪。需要帮助完成readCustomerFile,无法确定如何使用第二个扫描仪 以下是文件:Java 试图读入一个文件并获取同一行中的独立信息,java,arrays,Java,Arrays,我试图从这个文件中获取每一条单独的信息,将其分配给一个变量,使用数据创建一个Customer对象,然后将其添加到Customer对象数组中。这是一个项目,我必须使用数组,而不是ArrayList,我必须在readCustomerFile方法中使用2个扫描仪。需要帮助完成readCustomerFile,无法确定如何使用第二个扫描仪 以下是文件: 1 10001 Smith Sam 34.5 100.0 63.5 350.0 2 10002 Jones Pat 34.5 100.0 63.5 30
1 10001 Smith Sam 34.5 100.0 63.5 350.0
2 10002 Jones Pat 34.5 100.0 63.5 300.0
3 10003 King Kelly 34.5 100.0 63.5 300.0
4 10004 Jenkins Jordan 34.5 100.0 63.5 300.0 100.0
第一个数字是此人是什么类型的客户对象。1是首选客户,2是SilverPreferredCustomer,3是GoldPreferredCustomer。
以下是构造函数:
public class RewardsProcessor {
private Customer[] customers;
private String[] invalidRecords;
public RewardsProcessor() {
customers = new Customer[0];
invalidRecords = new String[0];
}
我的readCustomerFile方法,所以我需要帮助的方法应该使用2个扫描仪。一个读取文件,另一个逐行读取信息
public void readCustomerFile(String fileName) throws IOException {
Scanner scanFile = new Scanner(new File(fileName));
int category = 0;
int account = 0;
String name = " ";
Double[] purchase = new Double[100];
while(scanFile.hasNext()) {
String next = scanFile.nextLine();
这是客户和首选的SilverCustomer供参考
public Customer(String acctNumberIn, String nameIn) {
acctNumber = acctNumberIn;
name = nameIn;
purchases = new double[0];
}
public PreferredSilverCustomer(String acctNumber, String name) {
super(acctNumber, name);
category = "Preferred Silver Customer";
}
我很感谢你对我的问题有多了解 步骤1 步骤二 现在,内容数组包含文件中的所有信息 以单行方式访问信息 使用
1为什么要将数组初始化为空数组?新的双精度[0]是一个没有元素的数组。你遇到了什么问题?例外?输出不正确?在代码中的什么地方发生的?步骤1使用扫描仪获取线路。步骤2使用命令字符串[]split\u by\u spaces=str.split\\s;将行解析为字符串数组;。第3步循环遍历这个新数组,并根据该数组中存储的值生成一个对象。我会这样做的。
Scanner readFile=new Scanner(new File(filename);
String tempValue=""; // used for storing value while access data
String[] contents=new String[100];
int i=0;
while(readFile.hasNextLine())
{
contents[i]=readFile.nextLine(); // this array contain all your information in file line by line
i++;
}
String[] information=contents[0].split(" "); // now inforamtion[0] contain 1,inforamtion[1] contain 10001,.....