java - 无法确定数组中的索引
问题描述
将字符串添加到数组中,以确定列表是否通过增加字符串的长度来排序。如果不是,则打印违反此类排序的第一个元素的索引。如果数组中的字符串不同,则一切正常,例如,输入
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;
}
}
}
解决方案
你应该改变
list.indexOf(list.get(i+1))
至
i+1
因为如果在 中多次出现相同String
的List
内容,您希望返回违反排序的第一个元素的索引,即i+1
(而不是String
等于该元素的第一个元素的索引)。
顺便说一句,即使您的 中没有重复的元素,List
使用list.indexOf(list.get(i+1))
简单的i+1
.
推荐阅读
- pandas - 如何删除 Pandas 数据框的边框?
- regex - 正则表达式 - 通配符后的可选捕获组
- android - 如何从firebase获取数据到recyclerview
- javascript - onclick 不能正常工作
- android - ObjectDetectorTask:对象检测器管道已重置:MLKIT
- c++ - 在 C++ 中,“固定”大小的向量是否也有错误的大小(与内存大小相比)
- angular - Ionic 4 App 中未找到自定义 Angular (8) Pipe 问题
- stm32 - 无法从 ds18b20 读取温度
- swift - 使用 Swift macOS 为浏览器提供一个新的 url
- forms - PHPmailer 将电子邮件发送到 Outlook 帐户中的垃圾文件夹