我是一个完整的 Java 新手,我的代码中出现了一个非常奇怪的问题。目标是在一个数组中创建一个包含 20 个随机数的列表,显示这个数组并根据数组中的数据执行一系列计算。这必须通过 6 种方法来完成。除了最后一种方法外,一切似乎都运行良好。它旨在获取数组中的最小数字,但由于某种原因,它只输出一个 0。奇怪的是,对于上面的方法来说它工作得非常好,它收集了数组中的最高数字。
我试图对其进行故障排除,看看它是否可能来自具有空值的数组,但这不太可能,因为最高方法似乎工作正常。最低列表靠近底部。
感谢您的帮助,非常感谢这位新手。另外,如果您有任何其他很棒的评论,我愿意接受批评!
import java.util.Random;
public class Program7 {
public static void main(String[] args) {
final int listSize = 20; // List size
double total = 0; // Total
int[] ranList = new int[listSize]; // Array with random numbers
int highest = ranList[0]; // Highest variable
int lowest = ranList[0]; // Lowest Variable
randomNumberList(ranList); // Calls randomNumberList method
displayList(ranList); // Calls displayList method
total = totalList(total, ranList); // Calls totalList method
double averageList = listAverage(total, ranList); // Calls averageList method
highest = listHighest(ranList, highest); // Calls listHighest method
lowest = lowestList(ranList, lowest); // Calls lowestList method
// On screen output
System.out.println("\nHere's the total: " + total);
System.out.println("Here's the average: " + averageList);
System.out.println("Here's the highest number in the list: " + highest);
System.out.println("Here's the lowest number in the list: " + lowest);
}
/**
* Generates a random list
*
* @param ranList
*/
public static void randomNumberList(int[] ranList) {
for (int i = 0; i < ranList.length; i++) {
Random generator = new Random();
int ranNum = generator.nextInt(100) + 1;
ranList[i] = ranNum;
}
}
/**
* Displays list
*
* @param ranList
*/
public static void displayList(int[] ranList) {
System.out.println("Here is your random list: ");
for (int i = 0; i < ranList.length; i++) {
System.out.print(ranList[i] + " ");
}
}
/**
* Adds elements in list
*
* @param total
* @param ranList
* @return returns total of list added together
*/
public static double totalList(double total, int[] ranList) {
for (int i = 0; i < ranList.length; i++) {
total += ranList[i];
}
return total;
}
/**
* Finds average by dividing the total with the ranList.length
*
* @param total
* @param ranList
* @return result of the averaging
*/
public static double listAverage(double total, int[] ranList) {
double averageList = total / ranList.length;
return averageList;
}
/**
* Steps through array via loop and finds highest value
*
* @param ranList
* @param highest
* @return the highest value
*/
public static int listHighest(int[] ranList, int highest) {
for (int i = 0; i < ranList.length; i++) {
if (ranList[i] > highest) {
highest = ranList[i];
}
}
return highest;
}
/**
* Steps through array via loop and finds lowest value
*
* @param ranList
* @param lowest
* @return the lowest value
*/
public static int lowestList(int[] ranList, int lowest) {
for (int i = 0; i < ranList.length; i++) {
if (ranList[i] < lowest) {
lowest = ranList[i];
}
}
return lowest;
}
}