2015-10-04 77 views
1

我希望我的程序搜索一个对象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(); 
    } 

} 

输出有效,但在“请输入要补充的零件的ID”之后,例如,我必须输入零件ID 5次。 p126 p126 p126 p126 p126。那么它会提示补充数量。为什么要求ID 5次?而如何让这只是一次

+0

关于代码质量的注意事项:在一种方法中,您正在做太多事情。最重要的是:不要使用静态主要方法进行测试;而是学习如何编写**单元测试**。相信我,进入单元测试所需的相对较少的时间将会很快得到回报。 – GhostCat

+0

感谢提示@Jägermeister!我将详细研究如何编写未来的单元测试。目前,对于我的这部分任务(单向),一种方法可以。 – danielb

回答

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变量中。无论何时您再次需要它,请使用该变量。

+1

哦,是的,我明白了。同样的方式,我如何做选择变量?谢谢! – danielb

+0

@danielb是的,确切地说 –