2015-05-14 68 views
0

這是我的代碼:數組中的元素對稱

if (refractedAngleInDegrees > 60.0) 
{ 
    System.out.println ("The angle is making a reflection"); 

    //should reverse the array and make it into a palindrome-like array 
    for (int f = 0; f < gradient.length /2; f++) 
    { 
     double anglesReversed = angleArray[f]; 
     angleArray[f] = angleArray[gradient.length - f - 1]; 
     angleArray[gradient.length - f - 1] = anglesReversed; 

    } 
    for (int e = 0; e < gradient.length; e++) 

    { 
     //System.out.println(angleArray[e]); 
    } 

} 
else 
{ 
    System.out.println ("The angle is refracting"); 
} 
System.out.println(angleArray[x]); 
x++; 
} 

所以我堅持我的計劃。當它達到60時,我想讓它扭轉數值。

例如,如果我的[1 2 3 4 5]的數組,它會持續下去,直到它碰到5.

我希望它倒退和做[1 2 3 4 5 4 3 2 1](或直到陣列插槽結束),但我認爲我只是最終扭轉了這些值...

另外,我希望else語句在角度「進行反射」後停止。我會在那裏休息嗎?

這是之前的代碼,這可能是它錯誤的原因,因爲它在角度達到反射後繼續打印NaN。反射等於0,這也是錯誤的...

double incidentAngleInDegrees = 10.0; 
double incidentAngleInRadian; 
double refractedAngleInDegrees; 
double refractedAngleInRadian; 
double storedAngleInDegrees; 
double storedAngleInRadian; 
int x = 0; 


//loop for refraction 
double[] angleArray = new double [gradient.length]; 
while(x < 120) 

{ 
    incidentAngleInRadian = incidentAngleInDegrees * (Math.PI/180); // converting incident angle from degrees to radians 


    refractedAngleInRadian = Math.asin((indexArray[x] * incidentAngleInRadian)/indexArray[x + 1]); //getting the refracted angle in radians 

    refractedAngleInDegrees = refractedAngleInRadian * (180/Math.PI); 

    storedAngleInDegrees = refractedAngleInDegrees; // storing refracted angle in degrees 

    incidentAngleInDegrees = storedAngleInDegrees; // making the refracted angle in degree into the new incident angle in degrees 

    angleArray[x] = storedAngleInDegrees; 

} 

回答

1

如果要反映整個陣列,這裏是它的代碼:

class Rev { 
static int[] reflected(int[] a) { 
    int[] b = new int[a.length<<1]; 
    System.arraycopy(a, 0, b, 0, a.length); 
    int i, j; 
    for (j = a.length-1, i = 0; j>=0; j--, i++) { 
     b[a.length+i] = a[j]; 
    } 
    return b; 
} 

static void printArray(int[] a) { 
    for (int i = 0; i < a.length; i++) { 
     System.out.print(a[i] + ","); 
    } 
    System.out.println(); 
} 

public static void main(String[] args) { 
    final int[] a = {1, 2, 3, 4, 5}; 
    int[] b = reflected(a); 
    printArray(a); 
    printArray(b); 
} 
} 

如果要反映它的一部分,你只需要稍微修改這些代碼。希望這可以幫助。

的輸出是:

1,2,3,4,5, 
1,2,3,4,5,5,4,3,2,1,