
Write a program to accept the designations of 100 employees in a single dimensional array. Accept the designation from the user and print the total number of employees with the designation given by the user as input. Example: Trainee | Manager | Chef | Manager | Director | Manager Input: Manager Output: 3
Topic: Single dimensional String array — counting matches
Answer
import java.util.Scanner;
class Designation { public static void main(String args[]) { Scanner sc = new Scanner(System.in); String desg[] = new String[100]; int n, count = 0;
System.out.print("Enter the number of employees : "); n = sc.nextInt(); sc.nextLine();
System.out.println("Enter the designations :"); for(int i = 0; i < n; i++) desg[i] = sc.nextLine();
System.out.print("Enter the designation to search : "); String key = sc.nextLine();
for(int i = 0; i < n; i++) { if(desg[i].equals(key)) count++; }
System.out.println("Total number of employees with the designation " + key + " = " + count); } }
A linear search that counts every match instead of stopping at the first one — so there is no break in the loop.
The single most important point: compare Strings with equals(), never with ==. The == operator compares memory addresses, not text, and will give false even when two strings read identically. If the comparison should ignore capitals, use equalsIgnoreCase() instead.
The second point is the stray sc.nextLine() after reading n. nextInt() consumes the number but leaves the newline character in the input buffer, so the very next nextLine() would read an empty string and swallow the first designation. That extra call clears it. This single line catches out a great many candidates.
The array is declared with 100 places as the question demands, but only n of them are filled, so every loop runs to n and not to 100 — reading past n would give nulls.
desg[] String[100] - stores the designations of the employees n int - number of employees actually entered key String - designation to be searched for count int - counter for the number of matches found i int - loop variable sc Scanner - object used to read input