2017-06-10 18 views
0

这是我想出的代码。然而,我希望能够输出:数组值超过一个输出

  • (值)在槽x中。
  • (值)在时隙x中。

两个输出,如果(值)在两个时隙中可用样7.

  • (NUM)不是在数组中。

但不是两者都有。 任何人都可以帮忙吗?

public static void main(String[] args) { 
    int search, counter; 
    int num[]={3, 4, 5, 6, 7, 8, 10, 7, 9, 13}; 

    System.out.print("Array: "); 
    for (int count=0; count<num.length; count++) 
     System.out.print(+num[count] + " "); 

    Scanner in = new Scanner (System.in); 
    System.out.print("\nValue to find: "); 
    search = in.nextInt(); 

    for (counter = 0; counter < num.length; counter++){ 
     if (num[counter] == search) 
     { 
      System.out.println(search + " is in slot " + (counter + 1) + "."); 
     }   
    } 
    if (counter == num.length) 
     { 
      System.out.println(search + " is not in the array."); 
     } 
} 
} 

回答

1

虽然我觉得你应该问的另一个社区,如https://codereview.stackexchange.com/我可以给您一个建议这样一个问题:

使用一个布尔标志,检查是否之前已经发现了它。事情是这样的:

public static void main(String[] args) { 
    int search; 
    boolean found = false; 
    int num[]={3, 4, 5, 6, 7, 8, 10, 7, 9, 13}; 

    System.out.print("Array: "); 
    for (int count=0; count<num.length; count++) 
     System.out.print(+num[count] + " "); 

    Scanner in = new Scanner (System.in); 
    System.out.print("\nValue to find: "); 
    search = in.nextInt(); 

    for (int counter = 0; counter < num.length; counter++) { 
     if (num[counter] == search) 
     { 
     System.out.println(search + " is in slot " + (counter + 1) + "."); 
     found = true; 
     }   
    } 

    if (!found) { 
     System.out.println(search + " is not in the array."); 
    } 

    in.close(); 

} 

所以你只打印了“未找到”消息,当您无法找到通过数组直线穿越后的元素...

+0

假设使用布尔标志最合适的解决办法。 –

0

与您的代码的问题是,你检查如果计数器已达到阵列长度。总是会发生的事情。你应该检查你是否找到了一个值。

这应该做的伎俩:

public static void main(String[] args) { 
    int search, counter; 
    int num[]={3, 4, 5, 6, 7, 8, 10, 7, 9, 13}; 
    boolean wasFound = false; 

    System.out.print("Array: "); 
    for (int count=0; count<num.length; count++) 
     System.out.print(+num[count] + " "); 

    Scanner in = new Scanner (System.in); 
    System.out.print("\nValue to find: "); 
    search = in.nextInt(); 

    for (counter = 0; counter < num.length; counter++){ 
     if (num[counter] == search) 
     { 
      System.out.println(search + " is in slot " + (counter + 1) + "."); 
      wasFound = true; 
     } 
    } 
    if (!wasFound) 
    { 
     System.out.println(search + " is not in the array."); 
    } 
}