Computer Science, asked by ashwinilakhan6, 6 months ago

Using the switch statement in Java, write a program to display the name of the city according to the user's choice
D-Delhi, M - Mumbat , K - KolkataC - Chennai



who will answer correct i.will mark brainlist and follow him /her​

Answers

Answered by anindyaadhikari13
8

Required Answer:-

Question:

  • Using switch case statement in Java, write a program to display the name of the city according to the user's choice.
  • D - Delhi, M - Mumbai, K - Kolkata, C - Chennai.

Program:

This is an easy question. Read this post and get your answer.

Here comes the program.

import java.util.*;

public class SwitchCase

{

public static void main(String[] args)

{

//Creating objects of Scanner class.

Scanner sc = new Scanner(System.in);

System.out.print("Enter a character:");

// Taking character as input.

char ch = sc.next().toUpperCase().charAt(0);

switch(ch)

{

case 'D':

System.out.println("Delhi.");

break;

case 'M':

System.out.println("Mumbai.");

break;

case 'K':

System.out.println("Kolkata");

break;

case 'C':

System.out.println("Chennai.");

break;

default:

System.out.println("Invalid Choice. Please try again later. ");

}

sc.close();

}

}

How it's solved?

At first, we will import Scanner class. Scanner class is present in utility package of Java. It is used for taking input. Now, class and main() function is created. Here, I have created object of Scanner class at the beginning. Now, we will take the character as input from the user.

char ch = sc.next().toUpperCase().charAt(0);

Here, We will take a word as input,. Then we will convert it into upper case and then we will take the first letter as the character entered. Then using switch case, we will print the city name as per the choice i.e, D for Delhi, M for Mumbai, K for Kolkata and C for Chennai.

Note:- Letter written in bold are keywords.

Functions Used:

  1. next():- Used to take a word as input.
  2. toUpperCase():- Convert given string to upper case.
  3. charAt(indexValue):- Used to extract character from a string at a specific location.

Variable Description:

  • Only 1 variable is used i.e., ch variable(of character data type). Used to store the character entered by the user.

Output is attached.

Attachments:
Similar questions