[英]Accessing array in private class
我對如何訪問數組溫度感到困惑,以便將當前數組元素temp [i]與最大銷售量0進行比較,以確定哪個更大,每次嘗試在STEP 8和STEP 7中我都無法訪問temp ,我不想更改班級的知名度
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]);
}
}
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];
}
拿了安德魯·托比爾科(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];
}
感謝@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];
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.