2014-02-08 37 views
1

問題的答案:謝謝大家的幫助!如何添加我的循環中的所有結果

我在完成我的代碼時遇到了一些麻煩,主要是因爲我對編碼非常陌生,但仍然在努力。任何幫助是極大的讚賞!

我有3個問題:

  • 我的主要問題是,我不知道如何讓我的代碼從每個環路添加所有的總數。
  • 此外,循環開始後,它不會結束,當我輸入'0'時,但如果我結束循環,當我第一次運行循環它將工作。
  • 最後,我如何使小數總數以這種格式顯示; xx.xx而不是xx.xxxxxxx?

預先感謝您,我真的很感激所有幫助

import java.util.Scanner; 

public class takeOrders {//Find totals and average price 

    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 
     int euro; // what country the candy canes are from 
     int us;// what country the candy canes are from 
     int holder; //place holder for user input of location  
     int v110 = 0; //110v 
     int v240 = 0; //240v 
     int sum = 0, i = 1; 
     double total = 0; 
     double discount = 0; 

     do { 
      //Prompt what country the order is for 
      System.out.println("What country is the order for? (press '0' to see the Net Total of order) "); 
      System.out.println("1: Europe\n2: U.S."); 
      holder = input.nextInt(); 
      // 110 or 240 voltage 
      if (holder == 1) { 
       //How many boxes are ordered EUROPE 
       System.out.println("Input number of 240v boxes needed"); 
       v240 = input.nextInt(); 
       total = 2.40 * v240; 
       System.out.println("Order total: $" + total); 
      } else if (holder == 2) { 
       // How many boxes are ordered US 
       System.out.println("Input number of 110v boxes needed"); 
       v110 = input.nextInt(); 
       total = 2.40 * v110; 
      } 

      // Discount for U.S. 
      if (holder == 2) { 
       if (v110 >= 3) 
        discount = total * .05; 
      } else if (v110 >= 10) { 
       discount = total * .10; 
      } 
      if (discount > 0) { 
       System.out.println("Order total: $" + total); 
       System.out.println("Total with Discount: $" + (total - discount)); 
      } 
     } while ((v240 != 0) || (v110 != 0)); 

    } 
} 
+0

給你的問題添加更多標籤 –

回答

0

爲了完成環路我會用,而不是V110和V240這樣你不需要輸入一個國家,然後一個訂單金額持有人。 問題可能是由於如果您首先選擇美國並輸入一個值,則此值將保留,直到您再次輸入美國另一個金額,因此您的循環獲得最終結果,除非您選擇全部選擇相同的國家,然後選擇0作爲金額

爲了積累總你應該做的

total += 2.40*v240; 

total=total+(2.40*v240); 

這樣,總金額將獲得每個循環增加

爲了格式化您可以使用此代碼片段輸出:

DecimalFormat df = new DecimalFormat("#.##"); 
System.out.print(df.format(total)); 

我希望這可以幫助你的編程和Java熟悉。

0

一旦你捕獲輸入,您的病情而不可能是真實的,因此,無限循環。取而代之的

while ((v240 != 0) || (v110 != 0)); 

嘗試

while (holder != 0); 

要麼,你就需要重新V240 V110和每次重複循環時間爲零。

+0

謝謝!那就結束了循環! – user3287957

0

使用printf是最簡單的方法。

System.out.printf("%.2f", total); 

因此,對於您的情況:

System.out.printf("Order total: %.2f", total); 

您還可以使用DecimalFormat露面你要打印的數字。

import java.text.DecimalFormat; 

     DecimalFormat df = new DecimalFormat("#.##");   
     System.out.println("Order total: $" + df.format(total)); 
+0

我從來沒有使用過decimalFormat,我該如何開始呢?併爲system.out.printf(「%.2f」,總計);我只是把我需要的括號,然後添加'%.2f? – user3287957

+0

我在帖子中添加了printf示例。 printf是最簡單的使用。稍後將添加decimanFormat示例。 – Exploring

+0

爲您的情況添加了DecimalFormat。請導入十進制格式庫。如果有幫助,請投票給我的答案。 – Exploring

相關問題