Programming Example
Write a short program to input a digit and print it in words.
Study this program carefully to understand the logic, output, and explanation in a structured way.
Enter a digit (0-9): 5
Five
import java.util.Scanner;
public class DigitInWords {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a digit (0-9): ");
int digit = sc.nextInt();
switch (digit) {
case 0: System.out.println("Zero"); break;
case 1: System.out.println("One"); break;
case 2: System.out.println("Two"); break;
case 3: System.out.println("Three"); break;
case 4: System.out.println("Four"); break;
case 5: System.out.println("Five"); break;
case 6: System.out.println("Six"); break;
case 7: System.out.println("Seven"); break;
case 8: System.out.println("Eight"); break;
case 9: System.out.println("Nine"); break;
default: System.out.println("Invalid input! Please enter a single digit (0-9).");
}
sc.close();
}
}
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.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.