I keep getting this same error message, about my break being outside the switch or loop

Viewed 38

I am so lost and I am confused about where to put my break in my code to loop back to the start. I have been working on this for seven hours and have had no luck in trying to figure it out. I have checked other online resources and my text but nothing is working. I have it at the end but that just causes an error.

import java.util.Random;
import java.util.Scanner;

public class guess
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int guessednum;
System.out.print("Welcome to 'Guess That Number!!!!' ");
System.out.println("\nPlease enter a positive number to begin! :");
    int n = scan.nextInt();
        System.out.println("Enter the maximum amount of guesses you would like to     make during this game: ");
    int numguess = scan.nextInt();
Random r = new Random();
guessednum = r.nextInt(n)+1;
Scanner keyboard = new Scanner(System.in);
int g;
int t = 0;
System.out.println("Kindly think of a number within 1 and "+n);
System.out.println();
 do {
t++;
System.out.print("What do you think the number is? ");
g = keyboard.nextInt();
if (g == guessednum)
System.out.println("correct");
else if (g < guessednum)
System.out.println("the number is higher");
else if (g > guessednum)
System.out.println("the number is lower");
} while (g != guessednum && t < numguess);
if (g != guessednum)

System.out.println("You lost!");

System.out.println("\nEnter 1 to try again or 0 to exit:");
    int a;
    a= scan.nextInt();
    if(a==0)
break;

}
} 
2 Answers

You can not use break outside a loop/switch. Wrap your code inside main using a while loop and inside of it. Also you have to refactor the code. I can see multiple issues inside code.

The break statement is outside of the while statement. All the lines after the while should be inside the do block.

There's nothing to escape when there's no loop.

Related