0

My program is a simple divisibility checker for some practice. I am trying to take a user input if the user wants to re-run the program. When I run the program, it takes the user input for the number but the input statement for exiting the program is just not working. Please see the code below for reference.

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        while(true){
            Scanner input = new Scanner(System.in);

            System.out.print("Enter the number: ");
            int number = input.nextInt();

            if (number % 5 == 0)
                System.out.println("Divisible by 5");
            else if (number % 3 == 0)
                System.out.println("Divisible by 3");
            else
                System.out.println("not divisible by 3 or 5");
            System.out.println("Wanna do it again??(y/n)");
            String response = input.nextLine();
            if(response=="n")
                break;
        }
    }
}
greybeard
  • 2,015
  • 5
  • 20
  • 51
  • `nextInt()` followed by `nextLine()` causes this bug. Change your `nextInt()` into a `nextLine()`, then transform the resulting String into an int using `Integer.parseInt(String value)` – davidalayachew May 13 '21 at 07:34
  • 1
    Thankyou so much for the help. I changed nextLine() to next() and it worked. – Aditya W May 13 '21 at 07:43
  • I'm glad to hear it. I see that your question was closed. The link they attached to it also has some good information, so I encourage you to take a look. – davidalayachew May 13 '21 at 07:58

0 Answers0