【发布时间】:2020-02-29 18:29:10
【问题描述】:
我正在尝试读取文本文件并将其存储在对象的数组列表中,但我不断收到错误消息,提示我无法将字符串转换为项目,这是我正在使用的数组列表类型。我尝试了各种解决方案,但不太确定应该如何完成。我是编码新手,很快就会完成这项任务。有什么帮助!
private void loadFile(String FileName)
{
Scanner in;
Item line;
try
{
in = new Scanner(new File(FileName));
while (in.hasNext())
{
line = in.nextLine();
MyStore.add(line);
}
in.close();
}
catch (IOException e)
{
System.out.println("FILE NOT FOUND.");
}
}
我很抱歉没有添加 Item 类
public class Item
{
private int myId;
private int myInv;
//default constructor
public Item()
{
myId = 0;
myInv = 0;
}
//"normal" constructor
public Item(int id, int inv)
{
myId = id;
myInv = inv;
}
//copy constructor
public Item(Item OtherItem)
{
myId = OtherItem.getId();
myInv = OtherItem.getInv();
}
public int getId()
{
return myId;
}
public int getInv()
{
return myInv;
}
public int compareTo(Item Other)
{
int compare = 0;
if (myId > Other.getId())
{
compare = 1;
}
else if (myId < Other.getId())
{
compare = -1;
}
return compare;
}
public boolean equals(Item Other)
{
boolean equal = false;
if (myId == Other.getId())
{
equal = true;;
}
return equal;
}
public String toString()
{
String Result;
Result = String.format("%8d%8d", myId, myInv);
return Result;
}
}
这是我的arraylist的创建。 私有 ArrayList MyStore = new ArrayList ();
这是我的文本文件的示例。
3679 87
196 60
12490 12
18618 14
2370 65
【问题讨论】:
-
你能分享
Item类吗? -
能否添加
MyStore的代码? -
Stephanie,根据 Java 命名约定,您的变量名必须以小写字母开头。在此处查看有关它的信息 oracle.com/technetwork/java/codeconventions-135099.html 和此处 docs.oracle.com/javase/tutorial/java/nutsandbolts/…
-
如果此查询用于赋值,请学习java中的编组和序列化。这肯定会有所帮助。
-
Stephanie,也请显示文件行的示例。