Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can not determinate index in array

Tags:

java

arraylist

Strings are added to the array, to determine whether the list is ordered by increasing the length of the string. If not, print the index of the first element that violates such ordering. Everything works correctly if the strings in the array are different, for example, enter

113
13476
Neutral
wa

Answer: index (wa) 3 output.

but if it will be like this:

123
12345
123

Answer: index (123) - 0 but the correct answer is index 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;
        }
     }
}
like image 726
Anton Ku Avatar asked Apr 04 '19 06:04

Anton Ku


1 Answers

You should change

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

to

i+1

since if there are multiple occurrences of the same String in the List, you want to return the index of the first element that violates the ordering, which is i+1 (and not the index of the first String which is equal to that element).

BTW, even if there were no duplicate elements in your List, it would no sense to use list.indexOf(list.get(i+1)) instead of simply i+1.

like image 108
Eran Avatar answered Sep 21 '22 14:09

Eran