我有一个文件扫描程序类,即用于从客户列表中读取名称(我还有另一个文件,即用于读取Customer
对象,但这些文件正在读取正常) 。我的列表看起来像这样(我只是跳过数字,然后将名称读入字符串name
):
1,巴比
2,乔
3,苏
4,玛丽
5,维克多
但出于某种原因,当我使用toString()打印时,显示的唯一名称是Victor。我希望每个customer
对象都有自己的相应名称。
问题:如何让lineScanner
正确读取所有五个名称,然后将它们显示在toString()中?
//reads in customer name info
File customerList = new File("./src/Customers.txt");
Scanner fileScanner = new Scanner(customerList);
//while there is a new line, goes to next one
while(fileScanner.hasNextLine())
{
String line = fileScanner.nextLine();
Scanner lineScanner = new Scanner(line);
lineScanner.useDelimiter(",");
//while there is a new attribute to read in on a given line, reads data
while(lineScanner.hasNext())
{
lineScanner.next();
name = lineScanner.next();
customer1 = new Customer(ranking, name, tvTimeTotal1, exerciseTimeTotal1);
customer2 = new Customer(ranking, name, tvTimeTotal2, exerciseTimeTotal2);
customer3 = new Customer(ranking, name, tvTimeTotal3, exerciseTimeTotal3);
customer4 = new Customer(ranking, name, tvTimeTotal4, exerciseTimeTotal4);
customer5 = new Customer(ranking, name, tvTimeTotal5, exerciseTimeTotal5);
}
}
System.out.println(customer1.toString());
System.out.println(customer2.toString());
System.out.println(customer3.toString());
System.out.println(customer4.toString());
System.out.println(customer5.toString());
答案 0 :(得分:1)
这样的东西?
File customerList = new File("./src/Customers.txt");
Scanner fileScanner = new Scanner(customerList);
List<String> customerNames = new ArrayList<String>();
while(fileScanner.hasNextLine())
{
String line = fileScanner.nextLine();
Scanner lineScanner = new Scanner(line);
lineScanner.useDelimiter(",");
lineScanner.next(); // Discard number
customerNames.add(lineScanner.next());
}
for(String name : customerNames)
{
System.out.println(name);
}
答案 1 :(得分:0)
您实际上是在每个迭代中为每个Customer对象写入相同的数据,即您在第一次迭代中在所有对象上编写Bobby,依此类推。所以最终你在循环之后留下Victor在所有对象上。尝试使用数组或ArrayList
而不是此方法。参见@BertieWheen建议的那个。如果你是初学者而不是我建议你使用数组。
int i=0;
while(lineScanner.hasNext()){
lineScanner.next();
name = lineScanner.next();
customer[i++] = new Customer(ranking, name, tvTimeTotal1, exerciseTimeTotal1);
}
或者如果您对ArrayList
List customer=new ArrayList<Customer>();
while(lineScanner.hasNext()){
lineScanner.next();
name = lineScanner.next();
customer.add(new Customer(ranking, name, tvTimeTotal1, exerciseTimeTotal1));
}