如何使用collections、hashmap或treemap方法输出用户输入多次重复的元素(索引内容(?
我正在寻找线性方法,或者你可以说是数学方法,而不是现成的命令方法,有人能帮忙吗
import java.util.ArrayList;
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> arrayList = new ArrayList<>();
while (true) {
int input = scanner.nextInt();
if (input == -1) {
break;
}
arrayList.add(input);
}
System.out.println("search for? ");
for (int loopValue = 0; loopValue < arrayList.size(); loopValue++) {
int input2 = scanner.nextInt();
System.out.println(input2 + " is at index " + arrayList.indexOf(input2));
}
/样本输出应该类似于以下内容:
input user:
10
20
20
30
30
40
50
if -1 is inputted, the user will exit the loop
Number you are searching for in an array list?: the user again input the desired number 30
number 30 is at index 3
number 30 is at index 4
如何显示频繁数的索引,就像上面的^一样?
如果我正确理解你的问题,你可以做:
System.out.println("search for? ");
int input2 = scanner.nextInt();
for(int i =0; i<arrayList.size();i++){
if(arrayList.get(i)==input2){
System.out.println(input2 + " is at index " + i); //e.g. 30 is at index 3
}
}