数组的最小值返回0



我有问题弄清楚为什么返回我的最小值在我的数组结束为0。我检查了几个问题,同样的问题,但不能使用这些解决方案,因为我的数组是在一种方法中创建的,我的最小/最大值是在另一种方法中计算的。

无论如何,我可以保持我的最小/最大值在一个单独的方法,仍然得到一个非零的答案为我的最小值?此外,在processSalesReport方法中还有更多的代码,但我把它省略了,因为它无关紧要。提前感谢!

import java.util.Arrays;
import java.util.Scanner;
public class CarSalesReport {
int sum;
int count = 0;
int[] num = new int[1500];
String ans = "";
Scanner userInput = new Scanner(System.in);
public CarSalesReport(Scanner input) {
    String regex = "\d+|done";
    System.out.println("Type sales (type "done" when finished)");
    do{
        System.out.print("Sale Number " + (count + 1) +  ": ");
        ans = userInput.nextLine();
        while(!ans.matches(regex)){
            System.out.println("Please enter a positive number");
            ans = userInput.nextLine();
        }
        if(!ans.equalsIgnoreCase("done")){
            int ans1 = Integer.parseInt(ans);
            num[count] = ans1;
            count++;
        }           
    }while(!ans.equalsIgnoreCase("done"));
}
public void processSalesReport(){
    int max = num[0];
    for(int a=0;a<num.length;a++){
        if(max<num[a]){
            max=num[a];
        }
    }
    //This is where I'm having my problems.  
    int min = Integer.MAX_VALUE;
    for(int a=1;a<num.length;a++){
        if(min>num[a]){
            min=num[a];
        } 
    } 
    Arrays.sort(num);
    System.out.println("nMaximum sale: $" + max); 
    System.out.println("nMinimum sale: $" + min);
}
}

这是因为您的数组中有1500个条目,它们都被初始化为0。你要遍历所有的元素,试图找到最小值,而不是只遍历你显式填充的元素。

在计算最小值的循环中,更改

for (int a = 1; a < num.length; a++) {

for (int a = 0; a < count; a++) {

使您只查看已填充的条目。

最新更新