java - 数组包含该值多少次?

标签 java arrays

这是一个简单的程序,用于查找输入 x 值是否在数组中。
用户在数组中输入数字,然后输入一个数字来计算该数字在数组中重复的次数。 我有什么:

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 方法应该可以完成这项工作,但它没有。
我期望得到什么:

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.  

但是我的代码做了什么:

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 的默认值)值,因此出现问题

    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;
        //^^^^^^^^

    }

关于java - 数组包含该值多少次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49958163/

相关文章:

Java Spring 与 thymeleaf 复选框未选中时为空而不是 false

python 2D 数组,从 bool 掩码中切片/删除元素,并将结果保留为 2D 数组

arrays - 如何使用节点在 Mongoose 中获取深度嵌套数组中的对象

python - 从 numpy 结构化数组(数组中的元组列表)中删除列?

java - 如何根据用户当前位置从解析中获取数据?

java - Arduino 处理客户端无法将文件上传到 PHP 服务器

java - 如何获取具有文本和复选框字段的整个表的值 jsp 到 servlet

java - 如何在 HSQLDB 中创建特定日期?

c - C 中的二维数组是否可以按升序排序?如果是这样,怎么办?

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP