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;
}
}
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With