2016-02-26 91 views
2

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

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. 有没有办法来防止这种情况?

谢谢

+0

输入一个值您输入的值不数组 值中不存在您输入的数组不存在 您输入的值3存在于数组 –

+0

中请标记问题的答案或更新问题 – nullpointer

回答

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"); 
} 
3

您可能正在寻找break。即使找到您的num,整个循环也会遍历。并执行ifelse块中的任一个。这将帮助你:

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

,并可能以避免打印在任何情况下的价值是不匹配的,你可以从你的代码中删除else块。

+0

这仍会打印所有值直到您点击您输入的值。 – duffymo

+0

它会执行其他的东西,除非找到的值。这是OP正在寻找我相信。 – nullpointer

+0

来自问:“没有什么能阻止它完成时,它发现阵列中的数字” – nullpointer

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");