繁体   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