【问题标题】:Formatting output for ArrayList using an iterator使用迭代器格式化 ArrayList 的输出
【发布时间】: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


    【解决方案1】:

    使用带有逗号分隔符的 split 操作可以进一步拆分行数组元素。

    Iterator aio = animals.iterator();
    while (aio.hasNext()){
        String rowElement = (String) aio.next();
        String[] atomicElement = rowElement.split(",");
        // do something
    }
    

    【讨论】:

      【解决方案2】:

      您可以改用System.out.printfSystem.out.print。您可能可以查看this 以查看相同的示例。您可以将所有列的特定宽度设置为大于该列中的最大尺寸数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-18
        • 2014-03-26
        • 1970-01-01
        • 2011-10-05
        • 2014-07-07
        • 1970-01-01
        • 2016-08-23
        • 2020-03-16
        相关资源
        最近更新 更多