使用Java if-else

时间:2018-10-22 03:58:08

标签: java if-statement

这是我第一次使用堆栈溢出来提出问题。我是Java编程的初学者。我被安排在任务上,有人可以帮我解决吗?

因此,问题是使用java if-else将图像上的内容写入Java代码。但我没有得到这个问题。谁能解释?是否可以使用if-else进行编码?谢谢。

import java.util.Scanner;
public class MailOrderHouse{

    public static void main(String[] args){

       Scanner sc = new Scanner(System.in);
       double product1;
       double product2;
       double product3;
       double product4;
       double product5;

       System.out.println("Product price: ");
       double product_price = sc.nextDouble();

       System.out.println("Enter quantity sold: ");
       int quantity = sc.nextInt();

    }
}

我完全不明白这个问题。

2 个答案:

答案 0 :(得分:1)

您必须输入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); 
    }
}

但是无法理解您的输入格式。希望对您有所帮助。

答案 1 :(得分:1)

首先,向用户指示可用的产品及其各自的价格:

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();

用户提供的值与他/她想要的产品名称相关。现在只需要问用户所需的特定产品数量即可。

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)确保将总和的精度精确到小数点后两位显示在控制台上。您不希望在这种特殊情况下将类似21.422000522340的数字显示为货币值(在String.format()方法中进行读取)。