How to loop my code

I'm trying to do a game where the program randomly states two numbers and you try to multiply those numbers. I want my code to loop until I answer with -1 and when it does end I want it to state how many right I had.

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    int a = 0;
    int b = 0;

    int x = 1 + (int) (Math.random() * 9);
    int y = 1 + (int) (Math.random() * 9);
    int z = x * y;

    System.out.println(x + "*" + y);

    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter answer: ");
    int n = scanner.nextInt();
    scanner.close();
    if (n == -1) {
      System.out.println("You had " + a + " right out of " + b);
      return;
    }

    if (n == z) {
      a = a + 1;
      b = b + 1;
      System.out.println("Right");
    }
    else{
      b = b + 1;
      System.out.println("Wrong");
      }
  }
}

Did you consider?

Java While Loop

The while loop loops through a block of code as long as a specified condition is true:

Syntax:

while (condition) {
  // code block to be executed
}

I tried using a while loop by typing around my code

do {
my code
}while (n != -1)

But when I tried to run it didn't recognize the "n", I wanted to use the "n" input both for the answer and to end the code. So when I answer the program it loops until I answer with -1.

What happens when you print n after each input?

 int n = scanner.nextInt();
 System.out.println("My answer: " + n);

n is just my user input so it just mirrors whatever I've typed as my answer

Everything works fine except that I want the whole code to loop until I put n as -1

Yes it is easy to see what you want to do; and it should work it you put the code in the while construct I suggested.

If I do this and put while around my code it doesn't have any n to go after because the code hasn't run yet and if I add a variable it simply doesn't work

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    int a = 0;
    int b = 0;

    while (n != -1) {
    int x = 1 + (int) (Math.random() * 9);
    int y = 1 + (int) (Math.random() * 9);
    int z = x * y;

    System.out.println(x + "*" + y);

    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter answer: ");
    int n = scanner.nextInt();
    scanner.close();
    if (n == -1) {
      System.out.println("You had " + a + " right out of " + b);
      System.out.println(n);
      return;
    }

    if (n == z) {
      a = a + 1;
      b = b + 1;
      System.out.println("Right");
    }
    else{
      b = b + 1;
      System.out.println("Wrong");
      }
    }
  }
}

Maybe it's just easier to re type the code if you don't have any other suggestion