Skip to content
Advertisement

Something wrong with armstrong number java code

I wrote a code for school in java that verifies if a number is an armstrong number. I programmed it so that it runs as many times until the user inputs 0, at which the program will terminate. I am having 2 problems.

  1. The code only works the first time through, if the user inputs 371 (an armstrong number) the first time, it works, but after that it returns that the number is not an armstrong number.

  2. When the user inputs 0, it still shows the statement whether it is or is not an armstrong number, which I don’t want it to.

This is the code:

import java.util.Scanner; //import Scanner for user input   

public class Ch6Project {    

    public static void main(String[] args) {  

        int userNum, totalValue = 0, num, numLength; //declare variables that will be used
        String suserNum; //declare user input variable
        Scanner input = new Scanner(System.in); //declare a Scanner

        System.out.println("Welcome to the Armstrong Number Program."); //description
        System.out.println("nTo calculate an Armstrong number: ");
        System.out.println("t 1. Cube each digit of the number.");
        System.out.println("t 2. Take the sum of these cubes.");
        System.out.println("t 3. If the sum equals the number, it is an Armstrong Number.");
        System.out.println("t e.g. 3^3 + 1^3 + 7^3 = 317");

        do {
            System.out.print("nEnter a whole number (0 to quit): ");
            suserNum = input.nextLine(); //collect user input
            userNum = Integer.parseInt(suserNum); //parse user input
            numLength = suserNum.length(); //calculate length of user input

            for (int i = numLength; i > 0; i--) { //create loop to run for n times 
                num = Integer.parseInt(suserNum.substring(numLength - 1, numLength)); //get last digit of number
                totalValue += Math.pow(num, 3); //cube a digit 
                numLength--; //subtract userNum by 1 to get the rest of the digits
            }

            if (totalValue == userNum) { //if total value equals user input, it is Armstrong #
                System.out.println("Your number is an Armstrong number.");
            } else { //if total value does not equal user input, it is not an Armstrong #
                System.out.println("Your number is not an Armstrong number.");
            }

        } while (userNum != 0); //run loop until user input == 0
        input.close(); //close user input

    }
}

Advertisement

Answer

Change your code so that it breaks immediately after entry of the userNum

e.g.

userNum = Integer.parseInt(suserNum); //parse user input
if (userNum == 0) {
   break;
}

then you can also change your loop to a endless loop

while (true) {
   // your code
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement