2017-09-20 81 views
-1

如果我进入98意味着它会显示6位。如何查找数组中某个特定数字的位置?

public class OddEven { 
    public static void main(String args[]) { 
     int[] numbers = new int[] { 14, 23, 67, 10, 76, 5, 98, 13, 110 }; 
     for (int i = 0; i < numbers.length; i++) { 
      if(numbers[i]==14) 
       System.out.println(numbers[i]+"position 0"); 
      else 
       System.out.println(numbers[i]+"no. not in the list"); 
     } 
    } 
} 
+1

请删除javascript标记。 –

+1

那么,有什么问题? –

+0

只是返回我,你会有位置 – cralfaro

回答

0

首先,这是好事,有这样的事情,作为可测性等目的的独立的功能。这也使得代码更清晰。其次,如果你是通过循环,你可能不希望做system.out.println内环路

所以,你想是这样的:

public class IndexLookup { 
    int[] numbers = new int[] { 14, 23, 67, 10, 76, 5, 98, 13, 110 }; 
    public int indexOf(int query) { 
     for (int I = 0; I < numbers.length; i++) { 
      if (numbers[I] == query){ 
       return I; 
      } 
     } 
     return -1 
    } 
    public static void main(String[] args) { 
     if (indexOf(98) == -1) { 
      System.out.println("Not in list"); 
     } else { 
      System.out.printf("Found %d at position %d%n", 98, indexOf(98)); 
     } 
} 
+0

非常感谢你....我得到了答案.... –

0

只需使用的代码如下,将打印预期的结果如果你不想阵列考虑0的位置,你可以随时增加i值以我+ 1中出放声明“如果”存在的条件“的”循环内:-)

  boolean found = false; 
      int[] numbers = { 14, 23, 67, 10, 76, 5, 98, 13, 110 }; 
      Scanner sc=new Scanner(System.in); 

      System.out.println("Enter the number to search"); 
      int num =sc.nextInt(); 
      for (int i = 0; i < numbers.length; i++) { 
       if(numbers[i]==num){ 
        System.out.println(numbers[i]+" position "+i); 
        found =true; 
        break; 
       } 
      } 
      if(!found){ 
       System.out.println("Unable to find the Entered Number in the array"); 
      } 
相关问题