扫描仪输入也会为对象的另一个实例更改

the scanner input get changed also for another instance of an object

提问人:Abdulhadi Heib 提问时间:3/23/2023 最后编辑:Abdulhadi Heib 更新时间:3/24/2023 访问量:27

问:

因此,我想为每个 proudct 数量获得许多用户输入,并且当我为其中一个对象提供它时,下一个对象将变得相同。

我试过scanner.reset,但不起作用

用户应该选择一个选项,然后选择一个金额。

public  static void  addItem() {
        System.out.print("Please enter the grocery item number and the amount  #"+ customerList.size()+": ");
        printProducts();
      

            System.out.println("Enter your choice: ");
           int choice1 = scanner.nextInt();

            int amount1 = scanner.nextInt();

                if (choice1 ==0) {
                 
                    customerList.addProducts("milk",amount1);
                    
                }
                else if(choice1 ==1) {
                  
                    customerList.addProducts("cheese",amount1);
                   
                }
}

addProudcts 方法为:

public static void addProducts(String name,int amount){



        switch (name) {
            case "milk" :{
                productWithPrice milk = new productWithPrice("milk",6.5,amount);

                customerList.add(milk);
               // System.out.println(milk.getProductName() + "have been added to your shopping list");
            }
            case "cheese" :{
                productWithPrice cheese = new productWithPrice("cheese",15.0,amount);

                customerList.add(cheese);
                //System.out.println(cheese.getProductName() + "have been added to your shopping list");
            }
}
}

如果我输入牛奶的量(仅用于牛奶),它将变成奶酪的量(下一个 obect) 喜欢这个

0:product{  amount=2, product=  'milk', price=  13.0}
1:product{  amount=2, product=  'cheese', price=    30.0}
Java IF-语句 java.util.scanner

评论

1赞 Elliott Frisch 3/23/2023
当我将它用于其中一个对象时,它对于下一个对象变得相同不在这里,它没有。向我们展示一个可重复的例子。不是随机方法。

答: 暂无答案