請大家,我仍然在學習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);
}
}
}
}
兩個關鍵的事情要考慮。如果你想要'[i]'和'[i + 1]',然後循環到'lst.length - 1'。對於隨機數,你需要在兩個元素之間添加一個數字。 – KevinO
每個範圍有多少個值? –
@KevinO你是對的,但他的代碼中沒有'lst [i + 1]' – JackVanier