java - Java中查找数组中元素的出现次数

标签 java arrays

当用户键入一个值时,它会检查该值是否存在于数组中。

import java.util.Scanner;

public class array1 {
    public static void main(String[]args){
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter a value");
        int num = scan.nextInt();
        int [] arraynumbers = {1,2,3,4,5,6,7,8,9,10};
        for(int i = 0; i < arraynumbers.length; i++) {
            if (arraynumbers[i] == num){
                System.out.println("The value you have entered " + num + ", exists in the array");
        
            }else{
                System.out.println("The value you have entered does not exist in the array");
            }
        }
    }
}

所以,每当我输入一个数字来测试它时,它就会打印:

Enter a value
3
The value you have entered does not exist in the array
The value you have entered does not exist in the array
The value you have entered 3, exists in the array
The value you have entered does not exist in the array
The value you have entered does not exist in the array
The value you have entered does not exist in the array
The value you have entered does not exist in the array
The value you have entered does not exist in the array
The value you have entered does not exist in the array
The value you have entered does not exist in the array

我不是 100% 确定为什么会发生这种情况。

问题

  1. 是因为当它在数组中找到一个数字时,没有什么可以阻止它完成吗?
  2. 有办法防止这种情况发生吗?

谢谢

最佳答案

您可能正在寻找休息时间。即使找到了您的 num ,整个循环也会被遍历。并且执行 ifelse block 。这会对您有所帮助:

if (arraynumbers[i] == num) {
    System.out.println("The value you have entered " + num + ", exists in the array");
    break;
}

为了避免在值不匹配时打印任何内容,您可以从代码中删除 else block 。

关于java - Java中查找数组中元素的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35643088/

相关文章:

java - Android 单选按钮自定义属性

java - 对数螺旋

c - 数组、结构体、函数

java - Arrays.binarySearch() 如何在不排序的情况下工作

c - 将二维字符数组传递给 C 中的函数

c - 从函数返回结构体数组 - C 编程

java - Realm : Working with RealmChangeListener in Runnable

c# - 如何确定数学表达式的求值顺序?

java - 使用 Java 和 pdfBox 在 pdf 中搜索美元金额

C++:创建一个局部对象数组