我的高级for循环问题

时间:2015-10-04 10:15:11

标签: java for-loop

我希望我的程序搜索一个对象id(一次),然后使用我的replenish()方法更改数量但是它要求我在id之前多次键入id,我该如何解决这个问题?

import java.util.*;

class TestPart {



   public static void main(String[] args) {
         Scanner sc = new Scanner(System.in);
         List<Part> parts = new ArrayList<Part>();
         parts.add(new Part("p122", "Chain", 48, 12.50));
         parts.add(new Part("p123", "Chain Guard", 73, 22.00));
         parts.add(new Part("p124", "Crank", 400, 11.50));
         parts.add(new Part("p125", "Pedal", 38, 6.50));
         parts.add(new Part("p126", "Handlebar", 123, 9.50));
         System.out.println("part before stock level change - start");
         System.out.println(Part.toString(parts));
         System.out.println("To replenish type 'R' or to supply type 'S'");
         String choice = sc.nextLine();
         for(int i = 0; i<1; i++) {
             if (choice.equals("R")){
                System.out.println("Please enter ID of part you would like "
                        + "to replenish");

                for (Part part: parts) 
                    {
                     if(part!=null && sc.nextLine().equals(part.getID())){
                        System.out.println("Please enter replenish quantity");
                        part.replenish(sc.nextInt());
                     }
                }
             } else { 
                 System.out.println("You did not type 'R' or 'S'");
             }
         }
         /*System.out.println("Please enter ID");
         //parts.get(1).replenish(sc.nextInt());
        for (Part part: parts) {
             if(part!=null && sc.nextLine().equals(part.getID())){
                System.out.println("Please enter replenish quantity");
                part.replenish(sc.nextInt());
             }
         }*/
         System.out.println("-------------------------------------");
         System.out.println("part after stock level change - start");
         System.out.println(Part.toString(parts));
         System.out.println("end");

         sc.close();
     }

}

输出有效但仅在&#34之后;请输入您要补充的部分的ID&#34;例如,我必须输入部件ID 5次。 p126 p126 p126 p126 p126。然后它会提示补充数量。为什么要求5次身份证?以及我如何只做一次

1 个答案:

答案 0 :(得分:4)

基本上把这部分代码放在一个坏主意:

sc.nextLine().equals(part.getID())

进入循环,因为sc.nextLine()每次调用时都会等待用户的输入。

试试这个:

             if (choice.equals("R")){
                System.out.println("Please enter ID of part you would like "
                        + "to replenish");
                String input = sc.nextLine();
                for (Part part: parts) 
                    {
                     if(part!=null && input.equals(part.getID())){
                        System.out.println("Please enter replenish quantity");
                        part.replenish(sc.nextInt());
                     }
                }
             }

你会被问到一次,必须把它放进去一次。然后将其存储在String变量中。无论何时需要它,请使用变量。