2012-08-29 38 views
4

所以我是第一年的科學Sci學生,我必須創建一個程序,它會將一個數組加擾,然後重新排序。我幾乎可以正常工作,但由於某種原因,我的一個while循環不起作用,並且完全被繞過。我真的很新,所以所有的幫助表示讚賞。我已經排序,打印工作,爭奪只是給我一些麻煩。雖然環路被打翻?

import java.io.*; 
import java.util.Random; 
public class Driver03 
    { 
    public static void main(String[] args) 
     { 
     int[] array = {100, 101, 102, 103, 104, 105, 106, 107, 108, 109}; 
     print(array); 
     array = scramble(array); 
     print(array); 
     array = sort(array); 
     print(array); 
     } 
     public static void print(int[] apple) 
     { 
      for(int x = 0; x < apple.length; x++){ 
       System.out.println(apple[x]+""); 
       } 
     } 
     public static int max; 
     public static int maxIndex; 
     public static int temp; 
     public static int[] sort(int[] grape) 
     { 
      for(int y = grape.length; y > 0; y--){ 
      for(int x = 0; x < y; x++) 
       if (x==1){ 
        if (grape[x] > grape[x-1]){ 
         max = grape[x]; 
         maxIndex = x; 
         } 
        else{ 
         max = grape[x-1]; 
         maxIndex = x - 1; 
         } 
        } 
       else{ 
        if (grape[x] > max){ 
         max = grape[x]; 
         maxIndex = x; 
         } 
        } 
       temp = grape[maxIndex]; 
       grape[maxIndex] = grape[y-1]; 
       grape[y-1] = temp; 
       } 
      return grape; 
     } 
    public static int temp1; 
    public static boolean t; 
    public static boolean u; 
    public static int[] numbers; 
    public static int[] tangerine; 
    public static int[] scramble(int[] orange) 
     { 
     numbers = new int[10]; 
     tangerine = new int[10]; 
     Random rand=new Random(); 

     for(int x = 0; x < orange.length; x++){ 
      t=false; 
      while (t=false){ //For some reason being bypassed 
       int randn = rand.nextInt(9); 
       for(int y = 0; y < numbers.length; y++){ 
        if (numbers[x]==randn) 
         u = true; 
        } 
       if (! (u==true)) 
        { 
        numbers[randn] = randn; 
        tangerine[randn] = orange[x]; 
        t = true; 
        } 
       }   
      } 
      return tangerine; 
     } 

    } 

回答

6

t=false賦值falset並評估爲新值。因此你剛剛寫了while (false)

當比較相等時,您需要使用==

但是,在布爾值的情況下,僅使用while (!t)就好得多。由於缺少第二個=,這更具可讀性並且不太可能出錯。 「

+0

我也猜測你沒有在IDE中工作。例如,Eclipse會警告你這樣的錯誤。 – OrangeDog

0

使用:

while (! t){ 

要記住,使用==來比較值:)

2

一個等號:x = 4用於賦值給變量。

兩個等號:x == 6用於測試變量是否等於某個值。


您的if語句中的一些語法是非正式的。

這是非常奇怪的

if (! (u==true))

你可以用這個來代替:

if (!u)

更重要的是,你可以使用一個描述性的變量名,使其更具可讀性:

if (!found) { 
    shuffleItems(); 
} 

注意可讀性如何:如果找不到,則洗牌項目。

現在你的代碼文件本身!

+0

+1」for your code documents itself!「 – tilpner