Search code examples
javainputmismatchexception

How do i overgo a misMatchExeption in an armstrongnumber calculation in Scanner?


I have written the following code, with following conditions. I was not allowed to use any String or Math class, so I used for loops, to break the number down.

It works for e.g 153 and 54883 but for numbers like 4679307774 the Scanner Type gives me back a misMatchExeption. I do understand why, I tried using long type, the program works then, but does not (due to Two`s) give back a correct answer.

I want to know, how to solve that problem, or better said what other things I could try here.

Scanner sc = new Scanner(System.in);

    System.out.println("Please enter any Integer above zero here : ");
    System.out.println("Enter length of number, from 1 onwards: ");

    int num = sc.nextInt();
    int pow = sc.nextInt();

    int narziss = 0;  // TODO mismatchexeption
    int single;
    int a;

    do {
        a = 1;
        single = num % 10; // takes each chiffre from behind, for as long as for runs.
        System.out.println("single modulo : " + single);
        num = num / 10;

        for (int i = 0; i < pow; i++) {

            a *= single;
            System.out.println(a);
        }
        narziss += a;
        System.out.println("narziss: " + narziss);

    } while (num != 0);

    System.out.println(" if the last shown number, " +
            "is the same as you have typed in, " +
            "you found an so-called armstrong number! ");
    }
}

Solution

  • The problem i was asking, can be solved with a type other than Integer. With long for example... or floating point types.

    Be sure to change or cast all involved parts, like scanner, loops and so on.