如何并排输出两个不同长度的数组列表

我删除了我以前的帖子.. 这是我的问题的信息以及如何重现该问题


因为用户输入了正确数量的字符串以匹配 originalR6 长度,所以一切都变得很花哨。但是当说用户输入的字符串比 originalR6 少时,所以现在 originalR6 比 userInputR6 大。编译时返回索引超出范围 要查看手头的问题,请在 userInput 方法中注释掉 nomad,maverick,lion 并取消注释 nomad,maverick


    public static void main(String[] args) {

    TestMain main = new TestMain();

    main.addAll();


    //user input

    main.userInput();

    main.printAll();

}


ArrayList<String> originalR6 = new ArrayList<String>();

ArrayList<String> userInputR6 = new ArrayList<String>();


public void addAll() {

    //Our set list of characters

    Collections.addAll(originalR6,"nomad", "maverick", "lion");

}


public void userInput() {

    userInputR6.add("nomad");

    userInputR6.add("maverick");

    userInputR6.add("lion");

    //--------------

   // userInputR6.add("lion");

   // userInputR6.add("lion");

}


public void printAll() {

    for (int i = 0; i <originalR6.size() ; i++) {

        System.out.println((i+1) + ". " + originalR6.get(i) + "\t" + (i+1) + ". " + userInputR6.get(i));

    }

}

}


开满天机
浏览 83回答 2
2回答

宝慕林4294392

您应该打印到较小的索引,然后 ^rint 2 的较大列表,我使用printf它,因为它允许获得对齐:public void printAll() {&nbsp; &nbsp; int minSize = Math.min(originalR6.size(), userInputR6.size());&nbsp; &nbsp; for (int i = 0; i < minSize; i++) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.printf("%d. %-10s %d. %-10s%n", (i + 1), originalR6.get(i), (i + 1), userInputR6.get(i));&nbsp; &nbsp; }&nbsp; &nbsp; if (originalR6.size() < userInputR6.size()) {&nbsp; &nbsp; &nbsp; &nbsp; for (int i = minSize; i < userInputR6.size(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.printf("%d. %-10s %d. %-10s%n", (i + 1), "/", (i + 1), userInputR6.get(i));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } else if (originalR6.size() > userInputR6.size()) {&nbsp; &nbsp; &nbsp; &nbsp; for (int i = minSize; i < originalR6.size(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.printf("%d. %-10s %d. %-10s%n", (i + 1), originalR6.get(i), (i + 1), "/");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}要得到案子if1. nomad&nbsp; &nbsp; &nbsp; 1. nomad&nbsp; &nbsp; &nbsp;2. maverick&nbsp; &nbsp;2. maverick&nbsp;&nbsp;3. lion&nbsp; &nbsp; &nbsp; &nbsp;3. /&nbsp; &nbsp;案子 else if1. nomad&nbsp; &nbsp; &nbsp; 1. nomad&nbsp; &nbsp; &nbsp;2. maverick&nbsp; &nbsp;2. maverick&nbsp;&nbsp;3. lion&nbsp; &nbsp; &nbsp; &nbsp;3. lion&nbsp; &nbsp; &nbsp;&nbsp;4. /&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 4. lion&nbsp; &nbsp; &nbsp;&nbsp;5. /&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 5. lion&nbsp; &nbsp; &nbsp;&nbsp;

千巷猫影

索引两个“数组”数据时,如果您尝试索引数组/列表中的最后一个元素,您将得到index out of range,因为在最后一个元素之后只有深渊。for (int i = 0; i <originalR6.size() && i <userInputR6.size(); i++) {&nbsp; &nbsp; System.out.println((i+1) + ". " + originalR6.get(i) + "\t" + (i+1) + ". " + userInputR6.get(i));}i <userInputR6.size()作为附加条件添加到您的 for 循环条件中将停止您的index out of range错误,打印出的元素将简单地忽略较长数组/列表的其余部分。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java