M.Amir M.Amir - 3 months ago 7x
Java Question

User should input an integer by scanner class getting an input and check in if condition


  1. Get a input number from user.

  2. Validate the whether the given input is number or not.

  3. If it a number, then check Fibonacci series and display a message for the same.

  4. If the input is not number, then display, "please enter a number" and again ask for the input.

  5. User should give 'Q' to exit

  6. If a input is given. Do the above process and ask for the next input, till they hit 'Q'.

I have made an logic but unable to check in if condition

public static void main(String args[]) throws Exception {
boolean quit = false;
BufferedReader re = new BufferedReader(new InputStreamReader(System.in));
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number :");
int n;
while (!quit) {
if (sc.hasNextInt()) {
n = sc.nextInt();
while (n <= 0) {
System.out.println("*****Fibonacci Series*****");
int f1, f2 = 0, f3 = 1;
for (int i = 1; i <= n; i++) {

f1 = f2;
f2 = f3;
f3 = f1 + f2;
System.out.print(" " + f3 + " ");
quit = false;
} else if (!sc.hasNextInt()) {
System.out.println("That's not a number!");
quit = false;

} else(sc.hasNextInt().equals("q")) {
quit = true;

in if condition it throws error has .class expected


The if condition you are looking for is if (sc.hasNextInt())

After that you can call sc.nextInt();

The whole check could look like this:

        if (sc.hasNextInt()) {
            int num = sc.nextInt();
            //do something with num
        else if (sc.hasNext() && ("q".equals(sc.next())) ) {
                //do something

For details on Scanner please read JavaDoc.