繁体   English   中英

如何 output 从用户输入的数组列表中多次出现或列出的元素

[英]How to output an element that has occured or listed multiple times in an array list from a user input

在不使用 collections、hashmap 或树图方法的情况下,如何 output 用户输入多次重复的元素(索引内容)?

我正在寻找线性方法,或者您可以说数学方法而不是现成的命令方法,有人可以帮忙吗?

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));
    }

/ 示例 output 应类似于以下内容:

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
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM