2014-03-01 95 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"))