Home / Programs / Java Program to Check Spy Number
Programming Example

Java Program to Check Spy Number

👁 86 Views
💻 Practical Program
📘 Step by Step Learning
Study this program carefully to understand the logic, output, and explanation in a structured way.

Information & Algorithm

Given Input:

 int[] testNumbers = {112, 123, 22, 132};

Expected Output:

Checking Spy Numbers:
112 is NOT a Spy Number.
123 is a Spy Number!
22 is a Spy Number!
132 is a Spy Number!
Press any key to continue . . .

Program Code

public class SpyNumberChecker {

    // Method to check if a number is a Spy Number
    public static boolean isSpyNumber(int number) {
        int sum = 0, product = 1, digit;

        // Extract digits and calculate sum and product
        while (number > 0) {
            digit = number % 10; // Get the last digit
            sum += digit;       // Add to sum
            product *= digit;   // Multiply to product
            number /= 10;       // Remove the last digit
        }

        // Check if sum equals product
        return sum == product;
    }

    public static void main(String[] args) {
        // Test numbers
        int[] testNumbers = {112, 123, 22, 132};

        System.out.println("Checking Spy Numbers:");
        for (int num : testNumbers) {
            if (isSpyNumber(num)) {
                System.out.println(num + " is a Spy Number!");
            } else {
                System.out.println(num + " is NOT a Spy Number.");
            }
        }
    }
}

Output

Checking Spy Numbers:
112 is NOT a Spy Number.
123 is a Spy Number!
22 is a Spy Number!
132 is a Spy Number!
Press any key to continue . . .

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.