当用户键入一个值时,它会检查它是否存在于数组中。
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%确定为什么会这样。
谢谢
答案 0 :(得分:3)
您可能正在寻找break
。即使找到num
,也会遍历整个循环。并执行if
或else
块中的任何一个。这会对你有所帮助:
if (arraynumbers[i] == num) {
System.out.println("The value you have entered " + num + ", exists in the array");
break;
}
并且可能为了避免在值不匹配的情况下打印任何内容,您可以从代码中删除else
块。
答案 1 :(得分:2)
break语句绝对是关键。但是,如果要打印是否找到了数字,您可能需要考虑这样的事情:
int num = scan.nextInt();
int [] arraynumbers = {1,2,3,4,5,6,7,8,9,10};
String srchStr = "does not exist";
for(int i = 0; i < arraynumbers.length; i++) {
if (arraynumbers[i] == num) {
srchStr = "exists";
break;
}
}
System.out.println("The value you have entered " + num + ", " + srchStr + " in the array");
答案 2 :(得分:0)
当你将这个检查放在这样的循环中时,它意味着你检查数组中的每个数字:
for(int i = 0; i < arraynumbers.length; i++) {
}
你可以这样做:
List<Integer> values = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
if (values.contains(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");
}