簡體   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