首页 > 解决方案 > 无法确定数组中的索引

问题描述

将字符串添加到数组中,以确定列表是否通过增加字符串的长度来排序。如果不是,则打印违反此类排序的第一个元素的索引。如果数组中的字符串不同,则一切正常,例如,输入

113
13476
Neutral
wa

答案:索引(wa)3 输出。

但如果是这样的话:

123
12345
123

答案:索引 (123) - 0 但正确答案是索引 2

public class Solution {

    public static void main(String[] args) throws IOException {

             Scanner scan = new Scanner(System.in);
             ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            list.add(scan.nextLine());
        }
        int count = 0;
        for(int i = 0; i < list.size(); i++){
            if(count+2 > list.size()) {
                break;
            }
            if(list.get(i+1).length() <= list.get(i).length()){
                System.out.println(list.indexOf(list.get(i+1)));
                          break;
            }
                       count = count + 1;
        }
     }
}

标签: javaarraylist

解决方案


你应该改变

list.indexOf(list.get(i+1))

i+1

因为如果在 中多次出现相同StringList内容,您希望返回违反排序的第一个元素的索引,即i+1(而不是String等于该元素的第一个元素的索引)。

顺便说一句,即使您的 中没有重复的元素,List使用list.indexOf(list.get(i+1))简单的i+1.


推荐阅读