2 回答

TA貢獻1886條經驗 獲得超2個贊
首先,向用戶說明可用的產品及其各自的價格:
int productChoice = 0;
int quantity = 0;
double totalSum = 0.0;
System.out.println("Welcome To The Mail_Order House.");
System.out.println("Please select Product Number (1 to 5) you want to buy:\n");
System.out.println("1) Product Name 1: RM2.98");
System.out.println("2) Product Name 2: RM4.50");
System.out.println("3) Product Name 3: RM9.98");
System.out.println("4) Product Name 4: RM4.49");
System.out.println("5) Product Name 5: RM6.87");
這使用戶可以輕松查看可以購買的商品,從而做出有效的選擇。現在要求用戶輸入產品編號:
productChoice = sc.nextInt();
用戶提供的值與他/她想要的產品名稱相關?,F在只需詢問用戶該特定產品的所需數量即可:
System.out.println("What quantity of Product #" + productChoice + " do you want?");
quantity = sc.nextInt();
既然我們有了產品數量,就可以使用IF/ELSE IF來收集所選產品的價格并將其乘以用戶提供的數量以獲得該產品的總欠款:
if (productChoice == 1) {
// ......TO DO........
}
else if (productChoice == 2) {
totalSum += 4.50 * quantity;
// This is the same as: totalSum = totalSum + (4.50 * quantity);
}
else if (productChoice == 3) {
// ......TO DO........
}
else if (productChoice == 4) {
// ......TO DO........
}
else if (productChoice == 5) {
// ......TO DO........
}
else {
System.out.println("Invalid product number supplied!");
}
如您所見,您現在擁有向控制臺顯示所需輸出字符串所需的所有數據:
System.out.println("Mail-Order House sold " + quantity +
" of Product #" + productChoice + " for: RM" +
String.format("%.2f", totalSum));
在String.format("%.2f", totalSum)上述線可確保在總和2個精確到小數點后顯示給控制臺。21.422000522340在這種特殊情況下,您不希望像這樣的數字顯示為貨幣值(閱讀String.format()方法)。

TA貢獻1818條經驗 獲得超8個贊
您必須為已售產品數量輸入 5 個輸入值,為產品價格輸入 5 個輸入值。您必須計算這些產品的總價。您可以使用如下循環,而不是為 10 個輸入取 10 個變量:
import java.util.Scanner;
public class MailOrderHouse{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
double total = 0;
int totalProduct = 0;
for (int i = 0; i < 5; i++) {
int productQuantity = sc.nextInt();
double productPrice = sc.nextDouble();
total += productPrice;
totalProduct += productQuantity;
}
System.out.println("Mail-order house sell " + totalProduct + " product " + totalProduct + " for RM" + productPrice);
}
}
雖然無法理解您的輸入格式。希望能幫助到你。
添加回答
舉報