2014-03-01 56 views
0

我无法获得循环在代码中工作,所以如果用户说“否”,它会将他们带回第一个问题,他们必须回答“是”。如何获得循环工作

System.out.println("Adventurer soliders need your aid in Silverkeep can you deliver supplys to them? "); 

String choice; 
System.out.print("So can you deliver the supplys to them? "); 
choice = in.next(); 

if (choice.equals("Yes")) 
    System.out.println("Thank you so much, he are the supplys they need."); 
else if (choice.equals("No")) 
    System.out.println("But these soliders lives depend on these supplys! You must help us."); 

因此,如果他们说不,它会将他们带回到System.out.print行。

System.out.println("Adventurer soliders need your aid in Silverkeep can you deliver supplys to them? "); 
while (run) { 
    String choice; 
    System.out.print("So can you deliver the supplys to them? "); 
    choice = in.next(); 

    if (choice.equals("Yes")) 
     System.out.println("Thank you so much, he are the supplys they need."); 

    else if(choice.equals("No")) 
     System.out.println("But these soliders lives depend on these supplys! You must help us."); 
    run = true; 
} 

当我尝试运行上面的代码时,它只是用“所以你可以向他们提供耗材?”来控制台。

那么我哪里去错了..我尝试了多种事情,但没有运气。

+0

你如何 '在' 申报? –

+0

'run = true;'总是如此。无限循环 –

+0

不要在in.next – deviantfan

回答

2

你不会把{}放在你的if和else之后的东西的周围,所以它只做下一个语句。 run=true;总是在发生。

+0

如果他没有放在{}周围,那么代码必须运行无限的时间,因为run = true;将总是发生 –

+0

但他说“垃圾邮件”......不应该in.next()至少阻塞? –

0

现在尝试的代码,

System.out.println("Adventurer soliders need your aid in Silverkeep can you deliver  supplys to them? "); 

    while (run) { 
     String choice; 
     System.out.print("So can you deliver the supplys to them? "); 
     choice = in.next(); 

     if (choice.equals("Yes")) { 
      System.out.println("Thank you so much, he are the supplys they need."); 
      run = false; 
     } else if (choice.equals("No")) { 
      System.out.println("But these soliders lives depend on these supplys! You must help us."); 
      run = true; 
     } 
    } 

你忘了初始化与布尔值false运行值;

0

可以使用做........而循环,只要你想用户选择的基础上,你是否有再次或不及时的问题上作出决定。但首先去你必须要求用户........

System.out.println(“冒险家soliders需要你在silverkeep的援助,你可以提供给他们?”);

do { 
    String choice; 
    System.out.print("So can you deliver the supplys to them? "); 
    choice = in.next(); 

    if (choice.equals("Yes")) { 
     System.out.println("Thank you so much, he are the supplys they need."); 
     run = false; 
    } else if (choice.equals("No")) { 
     System.out.println("But these soliders lives depend on these supplys! You must help us."); 
     run = true; 
    } 
}while (run) 

,你需要声明运行

0

你可以尝试

do{ 
    //Your code 
}while(choice.equals("No"))