当用户键入一个值时,它会检查该值是否存在于数组中。
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% 确定为什么会发生这种情况。
问题
- 是因为当它在数组中找到一个数字时,没有什么可以阻止它完成吗?
- 有办法防止这种情况发生吗?
谢谢
最佳答案
您可能正在寻找休息时间
。即使找到了您的 num
,整个循环也会被遍历。并且执行 if
或 else
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/