-3

I have this code which is a minigame, you type a number and if is divisible by 5 you get a "Fizz" / if divisible by 3 you get a "Buzz" / and if divisible by both, you get a "FizzBuzz".

Now, i need help to end the "while(true)" loop, peacefully with a mesage like... "goodbye" whenever you enter the letter "X".

I would apreciate if you can add the aswer to the full code and a little explain of the code.

public class CLass {
public static void main(String[] args) {

    int number;
    Scanner scan = new Scanner(System.in);

while (true) {
        System.out.print("number:  ");

        number = scan.nextInt();

                if (number % 5 == 0 && number % 3 == 0)
                    System.out.println("FizzBuzz");
                else if (number % 5 == 0)
                    System.out.println("Fizz");
                else if (number % 3 == 0)
                    System.out.println("Buzz");
                else
                    System.out.println(number);
   }
}

}

Hrbz
  • 1
  • 1
  • Do you mean when somebody types a different letter and presses enter? It looks like that will end your loop in the current form. – matt Feb 27 '22 at 12:47
  • yes it did end, but it ends "brutally" with an error like: Exception in thread "main" java.util.InputMismatchException And i want to make it say : "goodbye" – Hrbz Feb 27 '22 at 13:26
  • Right now you're using "nextInt" instead you should use "next" or "nextLine" that returns a string. You could also "handle the exception". – matt Feb 27 '22 at 16:04

1 Answers1

1

You can do something like:

final Scanner scan = new Scanner(System.in);
String input;
do {
    input = scan.next();
    if(!Objects.equals(input, "x")){
       System.out.println("your input is: " + input);
       ...
    }
} while(!Objects.equals(input, "x"));
System.out.println("Goodbye");

And if you need to convert the string into int, take a look on some solutions here:

How to check if a String is numeric in Java

omer blechman
  • 277
  • 2
  • 16
  • i have no ideea how to implement that =))) Btw... i m new to this, and that code was an exercice i found on Youtube and i wanted to upgrade it like make a loop and end it with X and a line that says "Goodbye" – Hrbz Feb 27 '22 at 13:32
  • What do you expect that your loop will do? (I added the print that you want to my code) – omer blechman Feb 27 '22 at 15:09
  • 1
    The code provided is very basic! If you can't understand I suggest you go through some online tutorials to cover the basics first! @omerblechman – Emmanuel Mtali Feb 27 '22 at 15:13