D.Scheur D.Scheur - 1 month ago 5
Java Question

Having trouble with java loops

I am doing a project for school where i need to make a game about guessing the number from the computer. The problem I have is that my code won't print out the sentence "Het is fout" Which means that they are wrong. It also wont print the sentence that they tried to many times even tho it stops when they are over the limit. My teacher won't help me so I am desperate for some help. This is the code I wrote:

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;
}


Would appreciate any help

Answer Source

You have to invoke leesinvoer() once for each time you check it in your if() statement.

But your code is invoking leesinvoer() twice in each loop: once from while statement, and once from the if statement.

So, instead of while(leesinvoer() != toeval) do while(true), but better yet, (since this should give you a compiler warning saying "condition is always true",) do for(;;) which essentially loops forever.

Then, after each System.out() statement, (which essentially signifies a decision, which should end the loop,) do break; to exit the loop.

Goedenavond! C-:=