2017-02-22 87 views
-2

/*這是一個在線測試的問題,學生在其中寫入一個函數,該函數的答案由我的'correctfunction'驗證,而這個函數對學生是隱藏的。我想比較main方法中兩個函數的結果。 */在另一個方法中訪問一種方法的局部變量

import java.util.Arrays; 

    class SortArr 
    { 
    static int[] arr = new int[10]; 

public int[] sortin(int[] ans) 
{ 
     Arrays.sort(ans); 
     System.out.println(Arrays.toString(ans)); 
     return ans; 
    } 

    public int[] correctfunction(int[] sol) 
    { 
     Arrays.sort(sol);  
     System.out.println(Arrays.toString(sol)); 
     return sol; 
    } 

    public static void main(String[] args) 
    { 
     arr = new int[] {4,8,3,15,2,21,6,19,11,7}; 
     SortArr ob=new SortArr(); 
     ob.correctfunction(arr); 
     ob.sortin(arr); 

     if(Arrays.equals(ob.sol == ob.ans)) //non-static method //equals(Object) cannot be referenced from a static context 
//variable ob of type SortArr: cannot find symbol 
     System.out.println("correct"); 
     else 
     System.out.println("incorrect"); 
    } 
} 
+4

您的代碼太糟糕了。我剛剛編輯 –

+2

@sᴜʀᴇsʜᴀᴛᴛᴀ正在非常非常有禮貌 –

+0

編輯完成後,我才意識到,你只是在這裏放棄了代碼。 –

回答

0

首先Arrays.equals(parameter1, parameter2)需要兩個參數,以及你所做的是完全錯誤的。修復下面的代碼

public static void main(String[] args) 
    { 
     arr = new int[] {4,8,3,15,2,21,6,19,11,7}; 
     SortArr ob=new SortArr(); 
     int[] newSol = ob.correctfunction(arr); 
     int[] newAns = ob.sortin(arr); 

     if(Arrays.equals(newSol, newAns)) 
      System.out.println("correct"); 
     else 
      System.out.println("incorrect"); 
    } 
+0

這適用於我。謝謝@Lumnous_Dev – user1622611

0

該函數返回一個數組。所以當你調用該方法時,將返回的數組保存在一些數組變量中! 我已在您的代碼中進行了必要的更改。希望他們爲你工作。

import java.util.Arrays; 

    class SortArr 
    { 

     int arr1[]; 
     int arr2[]; 
    static int[] arr = new int[10]; 

public int[] sortin(int[] ans) 
{ 
     Arrays.sort(ans); 
     System.out.println(Arrays.toString(ans)); 
     return ans; 
    } 

    public int[] correctfunction(int[] sol) 
    { 
     Arrays.sort(sol);  
     System.out.println(Arrays.toString(sol)); 
     return sol; 
    } 

    public static void main(String[] args) 
    { 
     SortArr s = new SortArr(); //make an object of your class 
     arr = new int[] {4,8,3,15,2,21,6,19,11,7}; 
     SortArr ob=new SortArr(); 
     s.arr1 = ob.correctfunction(arr); // save the returned array 
     s.arr2 =ob.sortin(arr); // save the returned array 

     if(s.arr1 == s.arr2) 

     System.out.print("correct"); 
     else 
     System.out.print("incorrect"); 
    } 
} 
+0

謝謝@Vignesh Sriram – user1622611

相關問題