2017-06-10 46 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."); 
    } 
}