访问私有类

时间:2016-04-05 16:44:45

标签: java arrays private

我很困惑如何访问数组temp以便将当前数组元素temp [i]与max sales进行比较,以确定哪个更大,每次尝试我都无法访问temp IN STEP 8和STEP 7,我不想改变类的可见性

public class Sales {
    public static void main(String[] args) {
        int[] sales;

        sales = getSales();
        printSales(sales);
        printSummary(sales);
    }

    private static int[] getSales() {
        Scanner input = new Scanner(System.in);
        int[] temp;

        System.out.print("Enter the number of salespeople: ");
        temp = new int[input.nextInt()]; // Step 1

        for (int i = 0; i < temp.length; i++) // Step 2
        {
            System.out.print("Enter sales for salesperson " + (i + 1) + ": ");
            temp[i] = input.nextInt(); // Step 3
        }
        return temp; // Step 4
    }

    private static void printSales(int[] s) {
        System.out.println();
        System.out.println("Salesperson   Sales");
        System.out.println("-----------   -----");
        for (int i = 0; i < 5; i++) // Step 5
        {
            System.out.printf("%6d%12d\n", i + 1, s[i]); // Step 6
        }
    }

    private static void printSummary(int[] s) {
        int sum = 0;
        int max_sale = 0; // Salesperson with the most sales
        int min_sale = 0; // Salesperson with the least sales

        for (int i = 0; i < ________; i++) // Step 7
        {
            ____________ // Step 8

        }
        System.out.println();
        System.out.println("Total sales:  " + sum);
        System.out.println("Average sales: " + (double) sum / s.length);
        System.out.println("Salesperson " + (max_sale + 1) + " had the maximum sale with " + s[max_sale]);
        System.out.println("Salesperson " + (min_sale + 1) + " had the minimum sale with " + s[min_sale]);
    }
}

3 个答案:

答案 0 :(得分:3)

temp是一个已在main中创建并传递到printSummary(int[] s)方法的局部变量,因此您可以使用s访问它。

for (int i = 0; i < s.length; i++) { // STEP 7
    if (s[i] > max_sale) max_sale = s[i]; // STEP 8
    if (s[i] < min_sale) min_sale = s[i];
    sum += s[i];
}

答案 1 :(得分:2)

取了Andrew Tobilko代码并更改它以将索引保存到销售价值最高的人。实现这个替换你的循环将起作用。

for (int i = 0; i < s.length; i++) { // STEP 7
    if (s[i] > s[max_sale]) max_sale = i; // STEP 8
    if (s[i] < s[min_sale]) min_sale = i;
    sum += s[i];
}

答案 2 :(得分:0)

由于@andrew

,这在步骤7/8有效
int max = 0; 
int min = Integer.MAX_VALUE; 

for (int i= 0; i < s.length; i++) { 
sum += s[i]; 
if (s[i] > max) { 
max_sale = i; 
max = s[i]; 
} 
if (s[i] < min) { 
min_sale = i; 
min = s[i]; 
} 
}