[英]Having trouble with java loops
我正在做一個學校項目,我需要做一個關於從計算機猜測數字的游戲。 我的問題是我的代碼不會打印出句子“ Het is fout”,這意味着它們是錯誤的。 它也不會打印他們嘗試過多次的句子,甚至在超出限制時停止。 我的老師不會幫我,所以我迫切需要幫助。 這是我寫的代碼:
while(leesinvoer() != toeval)
{
aantalkeer = aantalkeer + 1;
if(leesinvoer() == toeval)
{
System.out.println("Het is goed het goede nummer was:"+ toeval);
}
else
{
System.out.println("Het is fout");
}
if(aantalkeer > pogingen)
{
System.out.println("U heeft te vaak beprobeerd");
}
}
System.out.println(toevalsgetalmaken(grens));
}
public static int toevalsgetalmaken(int grens)
{
Random toeval = new Random();
int toevalsgetal = toeval.nextInt(grens);
return toevalsgetal;
}
public static int leesinvoer()
{
String tekst = JOptionPane.showInputDialog(null,"Doe een gok","GOKJE",3);
int getal = Integer.parseInt(tekst);
return getal;
}
希望有幫助
每次在if()
語句中檢查leesinvoer()
時,都必須調用一次。
但是您的代碼在每個循環中兩次調用leesinvoer()
:一次來自while
語句,一次來自if
語句。
因此,代替while(leesinvoer() != toeval)
做while(true)
,但是更好的是,(因為這應該給您一個編譯器警告說“條件始終為真”,)執行for(;;)
,這實際上循環了永遠。
然后,在每個System.out()
語句之后(實際上表示一個決定,應該結束循環)之后都break;
退出循環。
Goedenavond! Ç - :=
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.