2017-05-15 80 views
0

請大家,我仍然在學習Java並且還不熟悉它的一些迭代技術。我想遍歷這個數組int [] lst = {34,23,7,14,10},以便它必須在數組中的每個元素之間生成隨機數。例如。它必須能夠列出34到23,23和7,7和14以及14和10之間的隨機值。 從昨晚到早晨,我一直在爲它工作,我需要非常幫助。我可怕的代碼粘貼在下面。數組中int元素的隨機整數

public class ArrayRange { 


    public static void main(String[] args) { 

     Random rand = new Random(); 

     int[] lst = {34, 23, 7, 14, 10}; 
     for(int i = 0; i < lst.length; i++){ 
      if (i == 0){ 
       int result = rand.nextInt(lst[i])+1; 
       System.out.println(result); 
      } 
      else { 
       int max = lst.length - 1; 
       System.out.println(rand.nextInt(max - lst[i])+ 1); 
      } 
     } 
    } 
} 
+0

兩個關鍵的事情要考慮。如果你想要'[i]'和'[i + 1]',然後循環到'lst.length - 1'。對於隨機數,你需要在兩個元素之間添加一個數字。 – KevinO

+0

每個範圍有多少個值? –

+0

@KevinO你是對的,但他的代碼中沒有'lst [i + 1]' – JackVanier

回答

1

試試這個:

public class ArrayRange { 

    public static void main(String[] args) { 

     Random rand = new Random(); 

     int[] lst = {34, 23, 7, 14, 10}; 
     for(int i = 0; i < lst.length-1; i++){ 
      int val = rand.nextInt(Math.max(lst[i], lst[i+1]) - Math.min(lst[i], lst[i+1])) + Math.min(lst[i], lst[i+1]); 
      System.out.println("(" + lst[i] + ", " + lst[i+1] + "):" + val); 
     } 
    } 
} 
+0

謝謝,但它沒有工作。它顯示錯誤「線程中的異常」主「java.lang.Error:未解決的編譯問題: \t at SumNum.main(ArrayRange.java:6) – Isan

+0

非常抱歉!非常感謝,它給了我後來的想法 – Isan

+0

上面的代碼工作正常,我在我的系統上測試它 – slal