-2

I am building a program and here's a bit of code:

Scanner input = new Scanner(System.in);

        begin:
        System.out.println("Enter first fraction: ");
        String fraction_1 = input.nextLine();
        System.out.println("Enter second fraction: ");
        String fraction_2 = input.nextLine();

        if(...){
        ...
        } else {
        ...
        break begin;

However in this, in the last line, 'begin' is colored red and an error is popping up:

Undefined label: begin

I want the program to jump to the line marked by begin, when else statement is true. I hope this is the correct way to do that. If not, what should I do?

DeathVenom
  • 384
  • 3
  • 22
  • `break;` is **not** `goto;` - Java does not have `goto` - What you need is called a loop. And `break;` is used to **end** loops. Not iterate them. – Elliott Frisch May 09 '20 at 16:56
  • If you break during a loop, you can use the break statement with a name to goto the named label to break out of multiple loops. – NomadMaker May 09 '20 at 17:02
  • You could use `break begin;` if you defined it in a scope where `begin` is visible: `begin` currently only labels the immediately following `System.out.println`. Put `{` after the `begin:`, and `}` after the `break begin;`. (It probably doesn't do what you mean, though). – Andy Turner May 09 '20 at 18:33

1 Answers1

2

break is used to terminate a loop, not to jump to an arbitrary part of the code. You could use a do-while loop to get the behavior you want. E.g.:

do {
    System.out.println("Enter first fraction: ");
    String fraction_1 = input.nextLine();
    System.out.println("Enter second fraction: ");
    String fraction_2 = input.nextLine();
} while (/* some condition isn't met */);
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 2
    @DeathVenom @Mureinik Note that you'll have to declare `fraction_1` and `fraction_2` outside of the loop for them to be visible later on. Actually you'll have to do this for the values to be available in the while condition. It's always bugged me that variables declared within a loop are not visible in the loop condition in Java. – RaffleBuffle May 09 '20 at 17:09