2017-03-25 10 views
-3

こんにちは私はこの課題に苦労しています。誰かがなぜ私のテストナンバー5が偽であると思われても、なぜ真実であるのかを教えてもらえますか?ありがとう。Javaメソッドと配列

これは質問です。

アレイ - has12 & linearIn

  1. intの配列が与えられると、1どこか後でアレイ2と配列である場合に真を返します。

  2. intの2つの配列が外側と内側の順にソートされている場合、innerのすべての数字が外側に表示される場合はtrueを返します。最良の解決策は、両方の配列がすでにソート順になっていることを利用して、両方の配列の単一の「線形」パスを作成することです。

これが私の出力である/問題

Test 1: true 
Test 2: true 
Test 3: false 
Test 4: true 
Test 5: true//needs to be false 
Test 6: true 

は、これは私のコード

public class Problems { 
public static void main(String[] args) { 
    int[] a = {1,3,2}; 
    int[] b = {3,1,2}; 
    int[] c = {3,1,4,5}; 
    int[] d = {1,2,4,6}; 
    int[] e = {1,2,4,4,6}; 
    int[] f = {2,4}; 
    int[] g = {2,3,4}; 

    boolean test1 = has12(a); 
    boolean test2 = has12(b); 
    boolean test3 = has12(c); 

    System.out.println("Test 1: " + test1); //should print true 
    System.out.println("Test 2: " + test2); //should print true 
    System.out.println("Test 3: " + test3); //should print false 
    System.out.println("Test 4: " + linearIn(d, f)); //should print true 
    System.out.println("Test 5: " + linearIn(d, g)); //should print false 
    System.out.println("Test 6: " + linearIn(e, f)); //should print true 

} 

//has12 method goes here 

public static boolean has12(int[] array) { 
    int i; 
    int x; 

    for(x=0;x<array.length;x++){ 
     if(array[x]==1){ 
     } 
    for(i=x+1;i<array.length;i++){ 
     if (array[i]==2) return true; 
    }  
    } 
    return false; 
} 
    //linearIn method goes here 
    public static boolean linearIn(int[] outer, int[] inner) { 
     int i; 
     int j; 
    for (i = 0; i < inner.length; i++) { 
    for (j =0; j < outer.length; j++) { 
    if (outer[j] == inner[i]) return true; 

    } 

    } 
     return false; 

    } 
} 

答えて

3

問題である。この時点思い付く:

if (outer[j] == inner[i]) return true; 

一致するものがあれば、関数は真を返し、あなたが望むものではありません。内部配列のすべての変数をチェックする必要があるからです。

  • すべての内部変数に対してisAppearブール値をチェックする必要があります。
  • 一致するものがない場合は、falseを返すことができます。
  • 一致する場合は、引き続き他の変数を確認してください。
  • 変数がなく、すべてがouterと一致する場合。 返信を返すことができます。

あなたはこれを試すことができます。

public static boolean linearIn(int[] outer, int[] inner) { 
    boolean isAppear; 
    for (int i = 0; i < inner.length; i++) { 
     isAppear = false; 
     for (int j = 0; j < outer.length; j++) { 
      if (outer[j] == inner[i]) 
       isAppear = true; 
     } 
     if(!isAppear) 
      return false; 
    } 
    return true; 
} 
+0

をああ知っておかなければOK!ご助力ありがとうございます! – livingundead

+0

問題はありません、あなたのお手伝いを歓迎します。 – ssorfonos