【发布时间】:2015-12-03 14:17:58
【问题描述】:
我在格式化我的 Java 程序的输出时遇到问题,我使用一个外部文件输入 ArrayList,然后使用迭代器生成输出。我使用以下数据创建了一个以逗号分隔的文本文件。
两栖类、青蛙、绿色、游泳 哺乳动物,狗,棕色,运行 鸟,猎鹰,棕色,苍蝇 鱼、鲑鱼、银、游泳
它被加载到程序中,然后需要使用迭代器来打印输出。我遇到的问题是试图让数组中的每个元素打印到一列中。输出当前如下所示。非常感谢任何有关如何格式化的帮助。
类型名称颜色动作
两栖类、青蛙、绿色、游泳
哺乳动物,狗,棕色,运行
鸟,猎鹰,棕色,苍蝇
鱼、鲑鱼、银、游泳
public class AnimalIO {
public static void main(String[] args) {
File file = new File("animals.txt");
ArrayList<String> animals = new ArrayList<>();
String animal;
// Structure used to read external data into internal ArrayList
try {
Scanner input = new Scanner(file);
while(input.hasNextLine())
{
animal = input.nextLine();
animals.add(animal);
}
}
catch(Exception e){
System.out.println("The input file \"animals.txt\" was not found.");
System.out.println(e.toString());
}
System.out.print("Type\t\tName\t\tColor\t\tAction\n");
System.out.print("---------------------------------------------------"
+ "----\n");
// Iterator structure used to print file
Iterator aio = animals.iterator();
while (aio.hasNext()){
Object element = aio.next();
System.out.print(element + "\t\n");
}
}
}
【问题讨论】:
标签: java arraylist iterator formatting