简单的命令行库存控制

时间:2018-08-12 15:47:21

标签: java

我想为超级市场开发一种命令行解决方案,以计算客户购买的总金额并显示出来,并且在每位客户购买之后,必须更新所有商品的初始库存。(我只使用了3个商品) 。。。但这只是计算总数而不更新库存。(而我需要使用while循环和for循环

import java.util.*;
public class newClass {
   public static void main(String args[]){
int qty1=100;
int qty2=200;
int qty3=300;

float price1=50.0f;
float price2=50.0f;
float price3=100.0f;

Scanner sc=new Scanner(System.in);
System.out.println("Input item1 quantity");
int no1=sc.nextInt();
System.out.println("Input item2 quantity");
int no2=sc.nextInt();
System.out.println("Input item3 quantity");
int no3=sc.nextInt();
float total=(no1*price1)+(no2*price2)+(no3*price3);
while(qty1>=no1 & qty2>=no2 & qty3>=no3 )
{
    qty1=qty1-no1;
    qty2=qty2-no2;
    qty3=qty3-no3;
}
System.out.println("your total is="+total);
   } 

}

1 个答案:

答案 0 :(得分:0)

您的代码有很多问题。首先,您打算根据内部初始数量进行循环,但不对其进行循环。更新数量后,您需要再次询问用户输入的数量。您没有正确关闭Scanner对象。

下面是代码的修改版本。希望这会有所帮助

public static void main(String args[]) {
    int qty1 = 100;
    int qty2 = 200;
    int qty3 = 300;

    float price1 = 50.0f;
    float price2 = 50.0f;
    float price3 = 100.0f;
    Scanner sc = new Scanner(System.in);
    while (qty1 > 0 && qty2 > 0 && qty3 > 0) {  // You any of the quantity is out of stock, exit loop
        System.out.println("\nCurrent Stock: qty1: " + qty1 + " qty2: " + qty2 + " qty3: " + qty3 + "\n");
        System.out.println("Input item1 quantity");
        int no1 = sc.nextInt();
        System.out.println("Input item2 quantity");
        int no2 = sc.nextInt();
        System.out.println("Input item3 quantity");
        int no3 = sc.nextInt();
        if (qty1 < no1) { // making sure that asked quantity is not more that in-house quantity
            no1 = qty1;
        }
        if (qty2 < no2) {
            no2 = qty2;
        }
        if (qty3 < no3) {
            no3 = qty3;
        }
        qty1 = qty1 - no1;
        qty2 = qty2 - no2;
        qty3 = qty3 - no3;
        float total = (no1 * price1) + (no2 * price2) + (no3 * price3);

        System.out.println("your total is=" + total);
    }
    sc.close();
}