簡體   English   中英

如何檢查鍵號在數組中是否重復?

[英]How to check whether the key number is repeated in the array?

如何從key(b)中獲取重復的數字,我的程序是這樣的,用戶輸入166456,key = 6,那么輸出必須像在數組中重復3次一樣是6,請還告訴我是否可以在不使用數組的情況下完成
我什至收到錯誤,因為int不能為int []

    int []a,i,j,count=0,b=0,n;
    Scanner sc=new Scanner(System.in);
    n=sc.nextInt(System.in);
    int []a=new int[n];
    for(i=0;i<n;++i)
    {
        a[i]=sc.nextInt();

    }
    System.out.println("Which nuber would you like to find:");
    b=sc.nextInt();
    for(j=0;j<n;++j)
    {
        if(a[i]==b)
        {
            ++count;
        }
        else
        {
            System.out.println("Not found");
        }
    }
    System.out.println("No of time "+b+" is repeated "+count);

您正在做一些錯誤的變量聲明。 如果將數組聲明為int []a則它將所有變量視為數組。 這就是為什么您得到錯誤。 您可以聲明為int a[]或在其他行上聲明其他變量。

請參考下面的代碼,

import java.util.Scanner;

public class Test {

    public static void main(String[] args) {
        int []a;
        int b=0, count=0;
        int i, j, n;
        Scanner sc=new Scanner(System.in);
        n=sc.nextInt();
        a=new int[n];
        for(i = 0; i < n; ++i)
        {
            a[i]=sc.nextInt();

        }
        System.out.println("Which nuber would you like to find:");
        b=sc.nextInt();
        for(j=0;j<n;++j)
        {
            if(a[j]==b)
            {
                ++count;
            }
            else
            {
                System.out.println("Not found");
            }
        }
        System.out.println("No of time "+b+" is repeated "+count);

    }

}

輸出量

6
1
6
6
4
5
6
Which nuber would you like to find:
6
Not found
Not found
Not found
No of time 6 is repeated 3

據我了解的要求,您需要有關從用戶輸入中找出數字總頻率的幫助。 (假設數字只能是0到9。如果我在這個假設上錯了,請糾正我)。

因此,為此,我們只能使用大小為10的整數數組來存儲每個數字的頻率。 例如,考慮總共輸入6位數字-“ 166456”。 我們的整數數組的值將是(從索引0到9)0100113000。因此,我們可以直接返回要搜索的數字的索引,在此示例中,返回array [6]的值為3。

    int[] num=new int[10]; // storing each digit's frequency
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt(); // count for total digits
    for(int i=0;i<n;i++){
        int index = sc.nextInt();
        num[index]++;
    }
    System.out.println("Which number you would like to find out?");
    int b = sc.nextInt();
    if(num[b]!=0)
        System.out.println("No. of time "+b+" is repeated "+num[b]);
    else
        System.out.println("Not found");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM