我正在尝试使用具有分隔符“\ s \ s”的Scanner将多种数据类型的文件读入ArrayList对象,但是它似乎没有按预期工作。我正在使用printf来查看数据是否正确存储,我稍后将用于计算的数据。数据似乎正确显示,但我仍然得到“不正确的文件格式”异常。循环似乎也有问题。使用对象的ArrayList时,我总是陷入困境。
示例文本文件:
item item descr 100 1.50
item2 item descr 250 2.50
item2 item descr 250 3.50
代码:
import java.io.*;
import java.util.*;
public class ReadItems
{
private Scanner input;
ArrayList<Item> item = new ArrayList<Item>();
//open text file
public void openFile()
{
try
{
FileReader in = new FileReader("Items.txt");
input = new Scanner(in).useDelimiter("\\s\\s");
}
catch( FileNotFoundException fileNotFound)
{
System.err.println( "Error opening file.");
System.exit(1);
}
}
//read file
public void readFile()
{
try
{
while ( input.hasNextLine())
{
item.add( new Item(input.next(), input.next(), input.nextInt(), input.nextFloat() ));
for (Item list : item)
{
System.out.printf("%-10s%-48s$%5.2f\n", list.getCode(), (list.getDecription()+ ", "+ list.getWeight()+ "g"), + list.getPrice());
//System.out.println(item);
}
}
}
catch ( NoSuchElementException elementEx)
{
System.err.println( "Incorrect file format.");
System.exit(1);
}
catch ( IllegalStateException stateEx )
{
System.err.println( "Error reading from file.");
System.exit(1);
}
}
public void closeFile()
{
if (input != null)
input.close();
}
}
输出:
item item descr, 100g $ 1.50
item item descr, 100g $ 1.50
item2 item descr, 250g $ 2.50
item item descr, 100g $ 1.50
item2 item descr, 250g $ 2.50
item2 item descr, 250g $ 3.50
文件格式不正确。
对不起,我觉得我做的很蠢。我没有在main
所在的测试类中运行该程序。
测试类:
public class TestReadItems
{
public static void main(String[] args)
{
ReadItems application = new ReadItems();
application.openFile();
application.readFile();
application.closeFile();
}
}
程序运行没有错误但是我似乎无法使while循环正常工作。输出增加了三倍。
答案 0 :(得分:1)
这是因为打印输出的for
循环位于while
循环内。因此,它读取文件的每一行并返回输出。因此,要更正,请从for
语句中替换输出while
循环,并在while
循环完成后写入。
答案 1 :(得分:0)
循环也可以在文件末尾炸掉垃圾。我在item.add()调用之后添加了对.nextLine()的调用,现在它对我来说很好。
while ( input.hasNextLine()) {
item.add( new Item(input.next(), input.next(), input.nextInt(), input.nextFloat() ));
for (Item list : item) {
System.out.printf("%-10s%-48s$%5.2f\n", list.getCode(), (list.getDecription()+ ", "+ list.getWeight()+ "g"), + list.getPrice());
}
input.nextLine(); // added
}