gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:10:38 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com