链表程序在从文本文件中读取行时只添加一个对象



我在这里遇到问题。当我从文本文件中读取并将项目添加到链表时,我试图添加多行,但由于某种原因,它在第一行之后停止。该程序逐行读取文件,将每个单词拆分为一个数组,并将该对象添加到链表中。当我打印时,它只打印文本文件的第一行。

package com.foodlist;
public class Food {
private String name;
private String group;
private int calories;
private double percentage;
public Food(String name, String group, int calories, double percentage){
this.name = name;
this.group = group;
this.calories = calories;
this.percentage = percentage;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public int getCalories() {
return calories;
}
public void setCalories(int calories) {
this.calories = calories;
}
public double getPercentage() {
return percentage;
}
public void setPercentage(double percentage) {
this.percentage = percentage;
}
public String toString(){
String result = "";
result = name + " " + group + " " + calories + " " + percentage + "n";
return result;
}
}public class FoodList {
private FoodListNode head;
private class FoodListNode{
public Food f;
public FoodListNode next;
public FoodListNode(Food f){
this.f = f;
this.next = null;
}
}
public FoodList(){
head = null;
}
public FoodList getFoodList(){
final String FILE_NAME = "foods.txt";
String[] item = null;
Scanner inFile = null;
try {
inFile = new Scanner(new File(FILE_NAME));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FoodList list = new FoodList();
while (inFile.hasNextLine()){
String line = inFile.nextLine().trim();
item = line.split("\s+");
if(item.length==4){
list.add(new Food(item[0], item[1], Integer.parseInt(item[2]), Double.parseDouble(item[3])));
}
}
inFile.close();
return list;
}
public void add(Food f){
FoodListNode node = new FoodListNode(f);
if (head == null){
head = node;
}
else{
FoodListNode tmp = head;
while (tmp.next != null){
tmp = tmp.next;
tmp.next = node;
}
}
}
public String toString(){
String result = "";
FoodListNode tmp;
for(tmp = head; tmp != null; tmp = tmp.next){
result += tmp.f;
}
return result;  
}
}
public class FoodMenu {

public static void main(String[] args) {
FoodList items = new FoodList();
FoodList list = items.getFoodList();
System.out.println(list);
}
}

问题是我在while循环中放的大括号:

if (head == null){
head = node;
} else {
FoodListNode tmp = head;
while (tmp.next != null)->{
tmp = tmp.next;
tmp.next = node;
}<-
}

我去掉了它们,现在它工作得很好。还没有研究为什么这个变化会修复它,但会更多地研究它。

相关内容

  • 没有找到相关文章

最新更新