0
我想要做的是根據用戶給定的值創建一個數組。用戶必須給出陣列的長度加上最大值和最小值。我設法讓程序達到輸出正確數量值(正確長度)的程度,但它只是繼續輸出完全相同的數字(即添加的最大值和最小值)。根據我的研究,我嘗試將它們轉換爲一個字符串,這樣就不會發生,但它仍然無法正常工作。我嘗試了幾種不同的方法,包括:Integer.toString,String.valueOf,並創建一個全新的字符串。任何幫助將不勝感激。這裏是到目前爲止的代碼:基於用戶給定的值範圍創建一個數組
public static void main(String[] args) {
//Create a Scanner object
Scanner input = new Scanner(System.in);
//Ask the user to enter the length of the array
System.out.println("Please enter the length of the array:");
int arraylength = input.nextInt();
//Ask the user to enter a max value
System.out.println("Please enter the max value:");
int max = input.nextInt();
//Ask the user to input the minimum value
System.out.println("Please enter the min value:");
int min = input.nextInt();
//Initialize the array based on the user's input
double [] userArray = new double[arraylength];
/**
*The program comes up with random numbers based on the length
*entered by the user. The numbers are limited to being between
*the minimum and maximum value.
*/
for (int i = min; i < userArray.length; i++) {
userArray[i] = Math.random() * max;
}
//This code is supposed to sort the array and print out all of the numbers in order,
//with minimum in the beginning and max in the end.
for (int i = 0; i < userArray.length; i++) {
selectionSort(userArray);
Integer.toString(min);
Integer.toString(max);
System.out.println(min + userArray[i] + max);
}
//This code uses the method average to find the average
average(userArray);
//Close Scanner
input.close();
}
public static double average(double[] data) {
double sum = 0;
for (int i = 0; i < data.length; i++) {
sum = sum + data[i];
}
double average = sum/data.length;
return average;
}
public static void selectionSort(double[] list) {
for (int i = 0; i < list.length - 1; i++) {
//Find the minimum in the list[i...list.length-1]
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i + 1; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
//Swap list[i] with list[currentMinIndex] if necessary
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
}
}
}
現在,經過我補充說,位與平均計算,該方案沒有工作一次,雖然它沒有計算平均值(所以它只是創造了最大和最小的一個數組結束,排序)。它似乎是一種僥倖,因爲這是完全相同的代碼,並且從那以後就沒有這樣做過。儘管平均代碼可能會影響其他代碼?
是的,它的Java。我改變了,對不起。我調整了代碼,現在它讀取:** bold ** selectionSort(userArray);對於(i = 0; i
Jupiter8
2014-10-06 12:42:24
在你的粗體部分而不是'Double.toString(userArray [])'你應該有'Double.toString(userArray [i])'。這樣你就不會將數組轉換爲字符串,但只有一個double。 – JoriO 2014-10-06 15:33:35