2015-10-25 33 views
-1

我想知道是否有人能告訴我 1.爲什麼當我輸入帶有小數位的weightNumber時,weightConverted不會將其轉換爲整數,即使我創建了變量它? 2.我怎樣才能以任何方式改善這個「程序」,謝謝!將double轉換爲int或甚至小數位

現在的問題是:

enter image description here

代碼:

import java.util.Scanner; 
public class cofee { 

    public static void main (String []args){ 


     double weightNumber = 0; 
     String packageType = ""; 
     String serviceType =""; 
     double totalFee = 0; 
     double weightConverted = Math.round(weightNumber); // <- this is the problem, should i put it somewhere else? 

     final double LETTERCOSTP = 12.00; 
     final double LETTERCOSTS = 10.50; 
     final double BOXCOSTP = 15.75; 
     final double BOXCOSTS = 13.75; 
     final double BOXWEIGHTP = 1.25; 
     final double BOXWEIGHTS = 1.00; 

     // input 
     Scanner input = new Scanner(System.in); 

     System.out.print("Enter package type (letter/box): "); 
      packageType = input.nextLine().toLowerCase(); 

     System.out.print("Enter type of service (standard/priority): "); 
      serviceType = input.nextLine().toLowerCase(); 

     switch(packageType) 
     { 
     case "letter": 
      System.out.print("Enter the weight in ounces: "); 
      weightNumber = input.nextDouble(); 
      break; 

     case "box": 
      System.out.print("Enter the weight in pounds: "); 
      weightNumber = input.nextDouble(); 
      break; 

      default: 
       System.out.print("WRONG PACKAGE TYPE !!!"); 
     } 



      // letter 
     if (packageType.equals("letter") && serviceType.equals("priority")) 
     { 
      totalFee = LETTERCOSTP; 
     } 
     if (packageType.equals("letter") && serviceType.equals("standard")) 
     { 
      totalFee = LETTERCOSTS; 
     } 


      // box 
     if (packageType.equals("box") && serviceType.equals("priority")) 
     { 
      totalFee = BOXCOSTP + ((weightConverted - 1.0) * BOXWEIGHTP); 
     } 
     if (packageType.equals("box") && serviceType.equals("standard")) 
     { 
      totalFee = BOXCOSTS + ((weightConverted - 1.0) * BOXWEIGHTS); 
     } 





     // display 

     System.out.println("The fee is € "+ totalFee + " for a package with"); 
     System.out.println("\tType: "+packageType); 
     System.out.println("\tService: "+serviceType); 
     System.out.println("\tOunces: "+weightConverted); 




    } 

} 

回答

0

double weightConverted = Math.round(weightNumber);將調用round()weightNumber值,這是0,因此它會將0舍入到...以及... 0,並將其分配到weightConverted

+0

然後你調用'nextDouble()',但不會改變'weightConverted'的值。 – Andreas

+0

但它只適用於整個號碼。 – thedumbone