2

对我的硬件问题的一部分感到困惑。看起来这很容易,但我不能指望它。我正在尝试以最大和最小销售额返回销售人员。我对如何做到这一点感到困惑。帮助将不胜感激。

import java.util.Scanner;
public class Cray {
    public static void main(String[] args){

        final int SALESPEOPLE = 5;
        int[] sales = new int[SALESPEOPLE];
        int sum, maxperson, minperson;
        int max = sales[0];
        int min = sales[0];



        Scanner scan = new Scanner(System.in);
        //Fill the 5 element array of sales with the user's input
        for (int i=0; i<sales.length; i++)
            {
            System.out.print("Enter sales for salesperson " + i + ": ");
            sales[i] = scan.nextInt();
            //Calculate the max and min sales
            //How do I return the salesperson i with the the max and min sales?
            if(sales[i] > max){
                max= sales[i];
            }
            if(sales[i] < min){
                min = sales [i];
            }


            }



        System.out.println("\nSalesperson   Sales");
        System.out.println("--------------------");
        sum = 0;
        for (int i=0; i<sales.length; i++)
            {
            System.out.println("     " + i + "         " + sales[i]);
            sum += sales[i];
            }

        System.out.println("\nTotal sales: " + sum);
        System.out.println("Average sales: " + sum/5);
        //WHere I want to print the max salesperson.
        System.out.println("Salesperson" +  );

          }

        }
4

4 回答 4

2

您可以在开始扫描输入之前存储索引计数声明并初始化两个int变量:

   int maxindex=Integer.MIN_VALUE,minindex=Integer.MIN_VALUE;

然后像这样将您的数组索引分配给它们:

   if(sales[i] > max){
       max= sales[i];
       maxindex = i;
   }
   if(sales[i] < min){
       min = sales [i];
       minindex = i;
   }

现在您可以直接获取具有最大和最小销售额的销售人员

  System.out.println("Max sales person "+sales[maxindex]);
  System.out.println("Min sales person "+sales[minindex]);

我在这里使用了一个非常简单的技巧,即存储数组索引。这是非常基本的方法,尽管可能有更优化的方法。

于 2012-10-20T17:09:29.423 回答
0

再定义两个变量:

        int maxSalePersonIndex = 0;
        int minSalePersonIndex = 0;

更新你if的:

        if(sales[i] > max){
            max= sales[i];
            maxSalePersonIndex  = i;
        }
        if(sales[i] < min){
            min = sales [i];
            minSalePersonIndex = i;
        }

最后,只需打印和的maxSalePersonIndexminSalePersonIndex

    System.out.println("Salesperson index with max sale = " + maxSalePersonIndex);
    System.out.println("Salesperson index with min sale = " + minSalePersonIndex);
于 2012-10-20T17:11:01.880 回答
0

目前在您的 for 循环中,您存储的是最大和最小销售额,而不是获得这些销售额的销售人员。因此,您应该存储imax/min中,而不是sales[i].

int max = 0, int min = 0

...

// in the for-loop
if(sales[i] > sales[max]){
    max = i;  // i.e. salesperson "i"
}
if(sales[i] < sales[min]){
    min = i;
}

...

System.out.println("Max salesperson: " +  max);
System.out.println("Min salesperson: " +  min);
于 2012-10-20T17:05:10.223 回答
0

您可以将支票调整为最大

   if(sales[i] > max){
       max = sales[i];
       maxPerson = i;
   }
于 2012-10-20T17:05:37.073 回答