C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Menu Driven - Composite Number / Smallest digit in Number Program - Java Programs

Using the switch statement, write a menu-driven program:

(i) To check and display whether a number input by the user is a composite number or not. (A number is said to be composite if it has one or more than one factor excluding 1 and the number itself.). Example: 4, 6, 8, 9, …

(ii) To find the smallest digit of an integer that is input:

Sample Input: 6524

Output: Smallest digit is 2.


For an incorrect choice, an appropriate error message should be displayed.

import java.util.Scanner; class Menu{ public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("1. Composite number"); System.out.println("2. Smallest digit"); System.out.print("Enter your choice: "); int choice = Integer.parseInt(in.nextLine()); switch(choice){ case 1: System.out.print("Number to be checked: "); int n = Integer.parseInt(in.nextLine()); boolean flag = false; for(int i = 2; i <= n / 2; i++){ if(n % 2 == 0){ flag = true; break; } } if(flag) System.out.println("Composite number"); else System.out.println("Not a Composite number"); break; case 2: System.out.print("Enter the number: "); n = Integer.parseInt(in.nextLine()); int d = n % 10; for(int i = n; i != 0; i /= 10){ if(d > i % 10) d = i % 10; } System.out.println("Smallest digit: " + d); break; default: System.out.println("Invalid choice!"); } } }

Output

 
 OUTPUT 1: 
1. Composite number
2. Smallest digit
Enter your choice: 1
Number to be checked: 12
Composite number 

 OUTPUT 2: 
1. Composite number
2. Smallest digit
Enter your choice: 2
Enter the number: 6524
Smallest digit: 2