gpt4 book ai didi

java - 填充对象的链接列表(程序运行时没有任何反应)

转载 作者:行者123 更新时间:2023-11-30 07:01:41 24 4
gpt4 key购买 nike

我正在尝试创建客户对象的链接列表,但我不完全确定如何填充该列表。当我运行程序时没有任何反应,并且程序似乎卡在 while 循环中?我真的不知道

这是我的客户类(class)

public class Customer {
private String name;
private String address;
private String num;
private int year;

public Customer(String name, String address, String num, int year) {
this.name = name;
this.address = address;
this.num = num;
this.year = year;
}
@Override
public String toString() {
return "Name: " + name + "\nAddress: " + address + "\nCustomer Number: " + num + "\nLast Order: " + year;

}
}

这是我的测试人员类(class):

import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.File;
import java.util.*;

public class CustomerRunner {
public static void main(String[] args) throws FileNotFoundException {
String name;
String address;
String num;
int year;
Customer customer;

LinkedList<Customer> lst = new LinkedList<Customer>();

Scanner in = new Scanner(new File("Customers.txt"));
Scanner input = new Scanner(System.in);

while(in.hasNext()) {
for (int i = 0; i < lst.size(); i++){
name = in.next();
address = in.next();
num = in.next();
year = in.nextInt();

customer = new Customer(name, address, num, year);
System.out.println(customer.toString());
//fill linkedList
lst.add(customer);
}
}
System.out.println("1");
System.out.println(lst.size());

}
}

println(1) 和 println(lst.size()) 只是为了尝试获得某种输出。

作为引用,这是我的 Customers.txt

Brooke MainStreet 123456789 2016
Adam MainStreet 234567890 2015
Zack MainStreet 123412341 2014
Cam MainStreet 453648576 2010
Tanya MainStreet 121212121 2005
Jason MainStreet 556574958 2004
Andrew MainStreet 777777777 2012
John MainStreet 999999999 2015
Jeff MainStreet 555444321 2010

最佳答案

你的 for 循环永远不会循环。 ArrayList lst 最初没有项目,因此当 for 循环运行时其大小为 0。外部 while 循环不断重复,因为扫描器永远不会在 for 循环失败时放弃任何标记。相反,根本不使用 for 循环,而是仅使用 while 循环来检查 Scanner 对象何时用完 token 。

例如,

    while (in.hasNextLine()) {
String line = in.nextLine();

// I scan here the line obtained, but also could split the String
// if desired
Scanner lineScanner = new Scanner(line);
String name2 = lineScanner.next();
String addr2 = lineScanner.next();
String num2 = lineScanner.next();
int year2 = lineScanner.nextInt();
lineScanner.close();

Customer cust2 = new Customer(name2, addr2, num2, year2);
lst.add(cust2);
}

关于java - 填充对象的链接列表(程序运行时没有任何反应),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40796820/

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