Java Online Compiler
Example: Harshad Number Checker in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Harshad Number Checker import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Create a Scanner object to read user input Scanner scanner = new Scanner(System.in); // Step 2: Prompt the user to enter a number System.out.print("Enter a number to check if it's a Harshad number: "); int number = scanner.nextInt(); // Step 3: Store the original number for the divisibility check int originalNumber = number; int sumOfDigits = 0; // Step 4: Calculate the sum of digits // Use a while loop to extract digits until the number becomes 0 while (number > 0) { int digit = number % 10; // Get the last digit sumOfDigits += digit; // Add the digit to the sum number /= 10; // Remove the last digit } // Step 5: Check if the original number is divisible by the sum of its digits if (sumOfDigits != 0 && originalNumber % sumOfDigits == 0) { System.out.println(originalNumber + " is a Harshad number."); } else { System.out.println(originalNumber + " is not a Harshad number."); } // Step 6: Close the scanner scanner.close(); } }
Output
Clear
ADVERTISEMENTS