数组包含该值多少次? [英] how many times the array contains the value?

查看:71
本文介绍了数组包含该值多少次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的程序,用于查找输入的x值是否在数组中。

用户在数组中键入数字,然后键入数字以计数多少次此数字在数组中重复。
我拥有什么:

It is a simple program to find if input x value is in the array or not.
The user types numbers into the array, after that types a number to count how many times this numbers repeats in the array. What I have:

public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
        int[] mas = new int[5];
        for (int i = 0; i < mas.length; i++) {
            System.out.print("Input of mas["+i+"]: ");
            int n = sc.nextInt();
        }
        valueX(mas);
        for (int i = 0; i < 10000; i++) {
           System.out.println("Would you like to continue (1=yes, 0=no)?");
        int n = sc.nextInt();
        if (n==1) {
            valueX(mas);
        }
        if (n==0) {
            System.out.println("Program terminated");
            sc.close();
            break;

        } 
        }

    }
    public static void valueX(int mas1[]){
        Scanner scanner = new Scanner(System.in);
         System.out.print("Input x: ");
        int x =scanner.nextInt();
        int count =0;
        for (int i = 0; i < mas1.length; i++) {
            if (x==mas1[i]) {
                count++;
            }


        }
         System.out.println("Value "+x+" appears "+count+" time(s) in the array.");
    }

valueX方法应该执行此工作,但不能。

我期望得到什么:

The valueX metod should do this work but it does not.
What I expect to get:

Input of mas[0]: 2
Input of mas[1]: 2
Input of mas[2]: 3
Input of mas[3]: 4
Input of mas[4]: 2
Input x: 2
Value 2 appears 3 time(s) in the array.  

但是我的代码会做什么:

But what my code does:

Input of mas[0]: 2
Input of mas[1]: 2
Input of mas[2]: 3
Input of mas[3]: 4
Input of mas[4]: 2
Input x: 2
Value 2 appears **0** time(s) in the array.  

您能找到错误吗?

推荐答案

您没有将输入值存储在数组中,因此您的数组具有所有 0 (默认值 int )的值,因此出现问题

You are not storing the input value in array so your array has all 0(default value of int) value, hence the issue

    int[] mas = new int[5];
    for (int i = 0; i < mas.length; i++) {
        System.out.print("Input of mas["+i+"]: ");
        int n = sc.nextInt();
        mas[i] = n;
        //^^^^^^^^

    }

这篇关于数组包含该值多少次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆