2012-10-20 104 views
-1

對不起,如果我很煩。但是我陷入了我的硬件問題的另一部分。我現在的任務是代替銷售人員0,銷售人員從1開始。我嘗試通過將字符串i解析爲整數並加1來解決此問題。看起來好像會起作用。但是,由於某些原因,計算min值是不正確的。它保持在0.我嘗試了一遍代碼,看看爲什麼,但我看不到它。如何在銷售員程序中返回銷售額最高的人員 - JAVA [PT。 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, randomValue, numGreater = 0; 
    int max = sales[0]; 
    int min = sales[0]; 
    int maxperson = 0; 
    int minperson = 0; 



    Scanner scan = new Scanner(System.in); 
    for (int i=0; i<sales.length; i++) 
     { 
     //To attempt print out the information of salesperson 0 and salesperson 1, I returned the integer value of i and added one. 
     System.out.print("Enter sales for salesperson " + Integer.valueOf(i+1) + ": "); 
     sales[i] = scan.nextInt(); 

     //max if statemnent works fine and is correct 
     if(sales[i] > max){ 
      max= sales[i]; 
      maxperson = i; 
     } 
     //For some reason max is calculating but not min. 
     if(sales[i] < min){ 
      min = sales [i]; 
      minperson= i; 
     } 


     } 



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

    System.out.println("\nTotal sales: " + sum); 
    System.out.println("Average sales: " + sum/5); 
    System.out.println(); 
    System.out.println("Salesperson " + Integer.valueOf(maxperson+1) + " had the most sales with " + max); 
    System.out.println("Salesperson " + Integer.valueOf(minperson+1) + " had the least sales with " + min); 
    System.out.println(); 
    System.out.println("Enter any value to compare to the sales team: "); 
    randomValue = scan.nextInt(); 
    System.out.println(); 
    for(int r=0; r < sales.length; r++){ 
     if(sales[r] > randomValue){ 
      numGreater++; 
      System.out.println("Salesperson " + Integer.valueOf(r+1) + " exceeded that amount with " + sales[r]); 
     } 

    } 
    System.out.println(); 
    System.out.println("In total, " + numGreater + " people exceeded that value"); 

     } 

    } 
+1

有趣。嗯。我爲數組的一個銷售值輸入了-1,並且它正確地計算了min。任何正整數返回爲min = 0。 – recheej

+1

您不會初始化最小值,因此它以0(缺省銷售[0]值)開始。你需要把一個很大的值作爲最小的第一個值, – roni

+0

這很有道理。但是,我試圖初始化銷售[5](數組的最大值),它給了我一個索引錯誤。 – recheej

回答

2

的問題是,min永遠不會設置爲所有積極的銷售將是> 0

你應該初始化min爲一個較大的值,這樣一個積極的銷售數字可以是小於最小在if語句中指定值:

if (sales[i] < min) { 

你可以使用:

int min = Integer.MAX_VALUE; 
+0

這確實有用。但是使用最大值方法不在我們正在進行的工作範圍之內。還有另一種方法可以做到嗎? – recheej

+0

這是執行此操作的標準方法,但您也可以在第一次迭代中設置「min」值。 – Reimeus