I need help writing a code using switch statement and not nested if-else. The co
ID: 3786018 • Letter: I
Question
I need help writing a code using switch statement and not nested if-else. The code should do the same asChar x
If (x == 'T'llx=='U')
Printf("lowest ");
Else if (x == 'h' llx =='H')
Printf("medium ");
Else if (x =='g'||x =='G')
Printf("upper ");
Else
Printf("highest "); I need help writing a code using switch statement and not nested if-else. The code should do the same as
Char x
If (x == 'T'llx=='U')
Printf("lowest ");
Else if (x == 'h' llx =='H')
Printf("medium ");
Else if (x =='g'||x =='G')
Printf("upper ");
Else
Printf("highest ");
Char x
If (x == 'T'llx=='U')
Printf("lowest ");
Else if (x == 'h' llx =='H')
Printf("medium ");
Else if (x =='g'||x =='G')
Printf("upper ");
Else
Printf("highest ");
Explanation / Answer
/**
* Java Program for Switch case for if-else if
*/
package com.chegg.tasks;
import java.util.Scanner;
public class SwitchCase {
public static void main(String[] args) {
while(true){
System.out.println("Enter your character?");
Scanner scanner=new Scanner(System.in);
char input=scanner.next().charAt(0);
switch (input) {
case 'T':
System.out.println("lowest"); break;
case 'U':
System.out.println("lowest"); break;
case 'h':
System.out.println("medium"); break;
case 'H':
System.out.println("medium"); break;
case 'g':
System.out.println("upper"); break;
case 'G':
System.out.println("upper"); break;
default: System.out.println("highest");
}
}
}
}
Explination:
1. If we wnat to read the character from key board,then you will take scanner like as in above progrem.
2.Then you use swith case rather than if ,else -if.where each case represents one if condition.
3. Here i took input char for reading charcter and based on the value of input variable case of the swith executes.
4. And finally default is the final else of your requirement.
Expected o/p:
Enter your character?
T
lowest
Enter your character?
U
lowest
Enter your character?
h
medium
Enter your character?
H
medium
Enter your character?
g
upper
Enter your character?
G
upper
Enter your character?
g
upper
Enter your character?
1
highest
Enter your character?