首页 > 解决方案 > 如何检查数组中键号是否重复?

问题描述

如何从键(b)中获取重复的数字我的程序是这样的,用户输入 166456 和键 = 6,然后输出必须像 6 在数组中重复 3 次请告诉我是否可以在没有数组的情况下完成
我什至收到错误 int cannot be to 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);

标签: javaarrays

解决方案


您正在做一些错误的变量声明。如果您声明一个数组,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

推荐阅读