0

I don't know why, but the below code makes the user run the code again, whether they choose to or not. I've tried many things, but it doesn't work correctly.

Thanks!

 public static void main (String [ ] args)
{


    boolean a = true;
    while (a)
    {
        Scanner scan = new Scanner(System.in);

        System.out.print("Enter an integer:  ");
        int x = scan.nextInt();



        System.out.print("\n\nEnter a second integer:  ");
        int z = scan.nextInt();

        System.out.println();
        System.out.println();

        binaryConvert1(x, z);



        System.out.println("\n\nWould you like to run this code again? Enter \"Y\" or \"N\".");
        System.out.print("Enter your response here:  ");

        String RUN = scan.nextLine();
        String run = RUN.toLowerCase();
        if (run.equals("n"))
        {
            a = false;
        }

        System.out.println();
        System.out.println();
    }
    System.out.println("Goodbye.");
}
arsb48
  • 513
  • 4
  • 9

1 Answers1

0

Scanner.nextInt() doesn't consume the line ending characters from the buffer, which is why when you read the value of the "yes/no" question with scan.nextLine(), you'll receive an empty string instead of the value the user entered.

A simple way to fix this is to explicitly parse the integer from raw lines using Integer.parseInt():

System.out.print("Enter an integer:  ");
int x = Integer.parseInt(scan.nextLine());

System.out.print("\n\nEnter a second integer:  ");
int z = Integer.parseInt(scan.nextLine());
Mick Mnemonic
  • 7,403
  • 2
  • 23
  • 27