Home > Back-end >  Why is my Beam number program giving the wrong output?
Why is my Beam number program giving the wrong output?

Time:08-20

A Beam number is a number in which the sum of the squares of the digits of the number is larger than the number itself.

For example: In the no. 25, sum of the square of digits = 2^2 5^2 = 4 25 = 29 (greater than the number accepted)

Hence 25 is a Beam number.

Here is my code:

import java.util.Scanner;
class test
{
    public static void main()
    {
        System.out.println("\f");
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number");
        int m = sc.nextInt(); 
        int sum  = 0;
        while (m > 0)
        {
            sum  = (m)*(m);
            m = m/10;
        }
        if (sum > m)
        {
            System.out.println("It is a Beam number");
        }
        else
        {
            System.out.println("It is not a Beam number");
        }
    }
}

The program compiles properly, but there is some problem in the logic, as it doesn't give the desired output. A picture of the output is given: enter image description here

51 is clearly not a Beam no. as the sum of the squares of its digits (25 1=26) is less than 51 itself. What changes do I make?

CodePudding user response:

Your while loop is destroying the information about the inputted number. Whenever you enter a number greater than 0, the sum will be greater than 0, but m will always be 0.

Use another variable, initialized to m, in the while loop to perform your calculations, so that m stays the inputted value, so that your comparison at the end is correct.

CodePudding user response:

Here is how you might have debugged this yourself. Notice the print statements.

class test // unrelated note:  by convention class names should start with
           // upper case letters.
{
    public static void main()
    {
        System.out.println("\f");
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number");
        int m = sc.nextInt(); 
        int sum  = 0;
        System.out.println("Before while loop.");
        System.out.println("m = "   m   ", sum = "   sum);
        while (m > 0)
        {
            sum  = (m)*(m);
            m = m/10;
        }
        System.out.println("After while loop.");
        System.out.println("m = "   m   ", sum = "   sum);
        if (sum > m)
        {
            System.out.println("It is a Beam number");
        }
        else
        {
            System.out.println("It is not a Beam number");
        }
    }
}

Using print statements in key locations and printing out various fields is the first and most common step in debugging programs.

  • Related