2015-03-03 71 views
1

我在我的代碼上找到一條錯誤消息,以查找支付$ 200 +佣金額的員工的總工資。一旦輸入了所有員工的總銷售額,就應該列出落入不同薪酬類別的員工數量。下面是代碼:非法轉換異常?

public static void main(String[]args){ 
    Scanner input = new Scanner(System.in); 
    int basePay = 200; //$200 starting amount of pay 
    int totalPay = 0; //total amount the employee will receive 

    System.out.print("Enter the amount of employees: "); 
    int employee = input.nextInt(); 

    int[]sales = new int[9]; //four different categories 

    for(int i = 0; i < employee; i++){ 
     System.out.println("Enter the current employee's gross sales: "); 
     int grossSales = input.nextInt(); 

     totalPay = (int) (basePay + (grossSales * 0.09)); //uses the formula for finding pay, and then casts it to an int 

     if(totalPay <= 299.99){ 
      sales[0]++; 
     } 
     else if(totalPay <= 399.99){ 
      sales[1]++; 
     } 
     else if(totalPay <= 499.99){ 
      sales[2]++; 
     } 
     else if(totalPay <= 599.99){ 
      sales[3]++; 
     } 
     else if(totalPay <= 699.99){ 
      sales[4]++; 
     } 
     else if(totalPay <= 799.99){ 
      sales[5]++; 
     } 
     else if(totalPay <= 899.99){ 
      sales[6]++; 
     } 
     else if(totalPay <= 999.99){ 
      sales[7]++; 
     } 
     else if(totalPay >= 1000){ 
      sales[8]++; 
     } 
    } 
    System.out.println("Total Sales\tAmount of employees"); 

    for(int i = 0; i < 11; i++){ 
     System.out.printf("%02d-%02d: ", i * 100, i * 100 + 99.99); 
     System.out.print("\t" + sales[i]); 
    } 

    System.out.println("Checking array: " + Arrays.toString(sales)); 
} 

這裏是確切的錯誤消息我得到:

00-Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.Double 
    at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source) 
    at java.util.Formatter$FormatSpecifier.printInteger(Unknown Source) 
    at java.util.Formatter$FormatSpecifier.print(Unknown Source) 
    at java.util.Formatter.format(Unknown Source) 
    at java.io.PrintStream.format(Unknown Source) 
    at java.io.PrintStream.printf(Unknown Source) 
    at chapter7.Sales_comission.main(Sales_comission.java:54) 

我相信這是值得做的雙重轉換,但我不能完全確定什麼是錯的它?任何人都可以幫我弄清楚什麼是錯的(它編譯沒有錯誤)?我也試過只有雙打(包括數組),但是這並沒有解決問題。

+0

我認爲申訴可能是關於將'%02d'應用於雙重表達式'i * 100 + 99.99'。 – 2015-03-03 03:18:35

回答

3

'd'用於整數,將其更改爲'f'或將第二個參數轉換爲整數。

System.out.printf("%02d-%02d: ", i * 100, (int)(i * 100 + 99.99)); 

查看Java String Formatter Doc瞭解詳情。

+0

它的工作,但現在它不再正確地計數值。 – person3122 2015-03-03 03:43:11

+0

您可以使用「%.2f」格式化float/double。即System.out.printf(「%02d - %2f:」,i * 100,i * 100 + 99.99); – Dongqing 2015-03-03 04:43:39