ADVERTISEMENT
ADVERTISEMENT

Java program to read gender (M/F) and print the corresponding gender using a switch statement

Given/input gender (M/F), we have to print the corresponding gender using a switch statement.
Submitted by Nidhi, on March 03, 2022

Problem Solution:

In this program, we will read a character from the user and print the corresponding gender using a switch statement.

Program/Source Code:

The source code to read gender (M/F) and print the corresponding gender using a switch statement, is given below. The given program is compiled and executed successfully.

// Java program to read gender (M/F) and print the 
// corresponding gender using switch statement

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner SN = new Scanner(System.in);
    char gender;

    System.out.printf("Enter gender (M/m or F/f): ");
    gender = SN.next().charAt(0);

    switch (gender) {
    case 'M':
    case 'm':
      System.out.printf("Male.");
      break;

    case 'F':
    case 'f':
      System.out.printf("Female.");
      break;

    default:
      System.out.printf("Unspecified Gender.");
    }
    System.out.printf("\n");
  }
}

Output:

Enter gender (M/m or F/f): m
Male.

Explanation:

In the above program, we imported the "java.util.Scanner" package to read input from the user. And, created a public class Main. It contains a static method main().

The main() method is an entry point for the program. Here, we read a character from the user using the Scanner class. Then we printed the corresponding gender.

Java Basic Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.