change this code from if, else to Switch case - java

How to change this using Switch case
int marks = 65;
if (marks < 50){
System.out.println("fail");
}
else if (marks >= 50 && marks < 60){
System.out.println("D grade");
}
else{
System.out.println("Invald!");
}

First of all, using switch with numeric values when the range is too broad (as with your example) is not the best way to go. Lets assume we switch marks in your example, we then should make a case for all the possible values that marks can have (0-100 in this case). As you can see, this is much much more work than using simple if-else.
However, if you still wish to do it, here's how you can go about it:
switch (marks)
{
case 0:
System.out.println("fail");
break;
case 1:
System.out.println("fail");
break;
case 2:
System.out.println("fail");
break;
//continue up to case 49
case 50:
System.out.println("D grade");
break;
case 51:
System.out.println("D grade");
break;
case 52:
System.out.println("D grade");
break;
//continue up to case 60... etc
}

First of all, switch and case statements are mainly used for checking a specific value, along with enum. For example:
enum RobotState {IDLE, ACTIVE, INACTIVE;}
...
switch (curr_state) {
case IDLE: ...
case ACTIVE: ...
case INACTIVE: ...
default: ...
}
In your example, I do not recommend using switch and case since you need to check if marks fall into a range, not if marks is a specific value. However, if you must use switch and case for your example, you can do the following:
switch (marks) {
case 0:
case 1:
case 2:
...
case 50: System.out.println("fail"); break;
case 51:
case 52:
...
case 60: System.out.println("D grade"); break;
default: System.out.println("Invald!");
}

Related

How can i use a switch case that has a case that does all the cases before

So i am doing a simple menu in main class where it has 10 options from 0 to 9, i am using a switch case to get the option and then execute a certain code, and number 9 is to do all the options in the menu.
How can that if option is 9, it does me all the cases before.
public static void main(String[] args) {
switch (option) {
case 1:
do A;
break;
case 2:
do B;
break;
case 3:
do C;
break;
case 4:
do C;
break;
case 5:
do C;
break;
case 6:
do C;
break;
case 9:
do case 1 ;
do case 2 ;
do case 3 ;
do case 4 ;
do case 5 ;
do case 6 ;
}
}
I am expecting that when option is 9, it executes all the cases before;
There are various ways to achieve what you need. I'll outline a few.
Use methods
This is simple, and somewhat clean and easy to maintain. All you need to do is wrap the code you would like to execute in each case in a separate method then call those methods from within the switch. This is exactly what functions are for.
switch(option){
case 1:
doA();
break;
case 2:
doB();
break;
...
// other cases
...
case 9:
doA();
doB();
...
// other method calls
...
break;
}
Switch to if statements
This is pretty self explanatory, just check if the option is each different case or option 9.
if(option == 1 || option == 9){
do A;
}
if(option == 2 || option == 9){
do B;
}
...
// other cases
...
(Mis)use breaks
This is fairly ugly and I wouldn't recommend it but it's really up to personal preference (and how easy to read and maintain you want the code to be in the future).
If option is 9, then we flip a flag to turn off all breaks in the switch statement. This effectively makes all other cases below it just execute linearly (as the breaks to leave the switch are disabled).
boolean isCase9 = false;
switch(option){
case 9:
isCase9 = true;
case 1:
doA();
if(!isCase9){
break;
}
case 2:
doB();
if(!isCase9){
break;
}
...
// other cases
...
I suggest defining a method (let's call it switchMethod) with the switch case - when all options are only 0 to 8.
public void switchMethod(option) {
switch (option) {
case 1:
do A;
break;
case 2:
do B;
break;
case 3:
do C;
break;
....
case 8:
do X;
break;
}
}
In the main:
if (option < 9) {
switchMethod(option)
} else {
for (int i = 0; i <9; i++)
switchMethod(i)
}
That way you won't write duplicate code and it will do the logic you requested.
Another way is doing duplicate code like that:
switch (option) {
case 1:
do A;
break;
case 2:
do B;
break;
case 3:
do C;
break;
case 4:
do C;
break;
case 5:
do C;
break;
case 6:
do C;
break;
case 9:
do A;
do B;
do C;
....
break;
}

About The switch Statement in Java

I'm still learning. Today I have a question in SoloLearn, into The switch Statement lesion:
int day = 3;
switch(day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
// Outputs "Wednesday"
and I thinks, I can have a example to remember about input and switch Statement: I want input a number, and 1 as Monday, 2 as Tuesday.... to 7 as Sunday, and repeat: 8 as Monday, 9 as Tuesday....
This is my code:
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner day = new Scanner(System.in);
if (day.nextInt()>7){
day.nextInt()=day.nextInt()%7;
}
switch(day.nextInt()){
case 1 :
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 0:
System.out.println("Sunday");
case 7:
System.out.println("Sunday");
break;
}
}
}
and error. My knowledge's not enough to fix this thing (I think so, because i'm a newbie and still learning). Can you expand for me, fix this thing and thanks for teach!
Have fun!
The problem is here:
if (day.nextInt()>7){
day.nextInt()=day.nextInt()%7;
}
You're trying to assign a value back to the method call day.nextInt(), which you can't do. Instead, try something like the following:
int dayNum = day.nextInt() % 7;
Also, your switch includes a case for dayNum == 7, which will never be the case.
As mentioned by #kolosy You are missing a break statement below case 0 and by writing day.nextInt() four times, you are actually asking the user to enter four times.
Also you cant day.nextInt()=day.nextInt()%7; do this. By doing it you're trying to assign a value back to the method call Change your code of main function to this
Scanner day = new Scanner(System.in);
int enteredDay = day.nextInt();
if (enteredDay > 7) {
enteredDay = enteredDay % 7;
}
switch (enteredDay) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 0:
System.out.println("Sunday");
break;
case 7:
System.out.println("Sunday");
break;
}
Add break after case 0:
case 6:
System.out.println("Saturday");
break;
case 0:
System.out.println("Sunday");
break;
If the value in switch() goes beyond 7 than you will get error as you have not provided any default case here. You can either do something like number%7to get the value always in case range.
You are missing a break statement below case 0. Java does not allow label fall-through like some other languages.
Also - you should be checking for your number being >= 7, not >7, or you'll never get a 0 on the second week. 8 % 7 is 1
NextInt() is a method .. you can't assign it a value
You need to use nextInt() once to get the input and store it in a variable. Every time you call nextInt() it would look for the next integer value entered.
Scanner day = new Scanner(System.in);
int dayInput = day.nextInt();
if (dayInput>7){
dayInput=dayInput%7;
}
switch(dayInput){
case 1 :
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 0:
System.out.println("Sunday");
case 7:
System.out.println("Sunday");
break;
}
You could solve this by creating an int value to set the input for day as day.nextInt() then you can do the math in the created variable and make the switch depending on that value, this should work:
Scanner day = new Scanner(System.in);
int dayVal = day.nextInt();
if (dayVal>7){
dayVal %= 7;
}
switch(dayVal){
case 1 :
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 0:
System.out.println("Sunday");
break;
}
}
As said before, you need to change 7 to 0 because you will never have a residue of 0, therefore you will never get a Sunday

How can I get this switch to pick just one of the 3 options?

System.out.println("Please make a selection between 1 and 3");
int choice = s.nextInt();
switch (choice)
{
case 3: System.out.println("Can a brother get some fries with that?");
case 2: System.out.println("Cheeseburger it is.... fatso");
case 1: System.out.println("Good choice, you could use a salad");
break;
default: System.out.println("Not a valid selection bruh");
}
switch (choice) {
case 3: System.out.println("Can a brother get some fries with that?"); break;
case 2: System.out.println("Cheeseburger it is.... fatso"); break;
case 1: System.out.println("Good choice, you could use a salad"); break;
default: System.out.println("Not a valid selection bruh"); break;
}
I literally just added the breaks after each case so it will exit your switch if it encounters either 1,2,3 or none of them.
You are missing the break statements...
You need a break; after each of the cases.
switch (choice)
{
case 3: System.out.println("Can a brother get some fries with that?");
break;
case 2: System.out.println("Cheeseburger it is.... fatso");
break;
case 1: System.out.println("Good choice, you could use a salad");
break;
default: System.out.println("Not a valid selection bruh");
break;
}

How to put characters beyond 9 in superscript in java?

So I am making a program in Java on a BlueJ environment that computes Binary expansion. However, I can't seem to figure out how to add powers more than 9 in the output.
If I have an input power of anything more than 9 the program goes haywire, presumably because there are no cases after 9.
Also, I personally feel my program in general is extremely inefficient but I just did it this morning and this was the first approach I saw, so if you see a way to make it more efficient than using switch case, that'd be great too.
This is my code so far. It's not all mine, but I'm not sure if intellectual property and stuff applies on here, so just putting it out there.
import java.util.*;
class Binomial_Theorem_Expansion
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the value of x in (x+a)^n");
int x=s.nextInt();
System.out.println("Enter the value of a in (x+a)^n");
int a=s.nextInt();
System.out.println("Enter the value of n in (x+a)^n");
int n=s.nextInt();
System.out.println ("The expanded answer is");
int r=0;
int powx=n;
while (r<=n)
{
long nCr=calculatenCr(n,r);
if(nCr!=-1)
{
double y=Math.pow((double)x,(double)n-r);
double z=Math.pow((double)a,(double)r);
switch (powx)
{
case 0: System.out.print ("("+nCr*y*z);
break;
case 1: System.out.print ("("+nCr*y*z+"x");
break;
case 2: System.out.print ("("+nCr*y*z+"x\u00B2");
break;
case 3: System.out.print ("("+nCr*y*z+"x\u00B3");
break;
case 4: System.out.print ("("+nCr*y*z+"x\u2074");
break;
case 5: System.out.print ("("+nCr*y*z+"x\u2075");
break;
case 6: System.out.print ("("+nCr*y*z+"x\u2076");
break;
case 7: System.out.print ("("+nCr*y*z+"x\u2077");
break;
case 8: System.out.print ("("+nCr*y*z+"x\u2078");
break;
case 9: System.out.print ("("+nCr*y*z+"x\u2079");
break;
case 10: System.out.print ("("+nCr*y*z+"x\u2071\u00B2");
break;
}
switch (r) {
case 0: System.out.print (")");
break;
case 1: System.out.print ("y"+")");
break;
case 2: System.out.print ("y\u00B2"+")");
break;
case 3: System.out.print ("y\u00B3"+")");
break;
case 4: System.out.print ("y\u2074"+")");
break;
case 5: System.out.print ("y\u2075"+")");
break;
case 6: System.out.print ("y\u2076"+")");
break;
case 7: System.out.print ("y\u2077"+")");
break;
case 8: System.out.print ("y\u2078"+")");
break;
case 9: System.out.print ("y\u2079"+")");
break;
}
r++;
if (r<=n)
{
System.out.print ("+");
}
powx--;
}
}
}
public static long calculatenCr(int n,int r)
{
long res=1;
if(n>=r)
{
res=getFact(n)/(getFact(n-r)*getFact(r));
return res;
}
else return -1;
}
public static long getFact(int n)
{
long f=1;
for(int i=n;i>=1;i--)
{
f*=i;
}
return f;
}
}
Thanks for any constructive input. :)
presumably because there are no cases after 9.
Your code is using UNICODE superscript characters, and the cases that you have cover only numbers zero through ten for x and zero through nine for y.
You can fix this by defining a method that produces a superscript UNICODE conversion of a multidigit number, and calling it from both places where you need to produce such representation:
switch (powx) {
case 0: System.out.print ("("+nCr*y*z);
break;
case 1: System.out.print ("("+nCr*y*z+"x");
break;
default: System.out.print ("("+nCr*y*z+"x"+toSuperscript(powx));
break;
}
The other switch (i.e. switch (r)) should be converted in a similar way.
You can implement String toSuperscript(int n) by producing a decimal representation of n, and then replacing '0' with '\u2070', '1' with '\u00B9', and so on.

how to add while loop in switch statement when using dialog boxes?

Here I have some problem when I use while loop in switch statement using dialog boxes. Some statements are unreachable and dialog boxes not appeared. Please help me! And also can do some correction on my code.
This the simple code that I made:
public static void main(String[] args)
{
// prompt and read first number from user
String no = JOptionPane.showInputDialog(null, "Enter the number");
int num = Integer.parseInt(no); //convert string to number
switch (num)
{
//display result
default: JOptionPane.showMessageDialog(null,"fail"); break;
case 1: JOptionPane.showMessageDialog(null,"c=a+b"); break;
case 2: JOptionPane.showMessageDialog(null,"c=a/b"); break;
case 3: JOptionPane.showMessageDialog(null,"c=a*b"); break;
case 4: JOptionPane.showMessageDialog(null,"c=a-b"); break;
}
}
The cases in a switch/case are evaluated in the order you put them. default matches all cases. Since you have that first and that case does something before breaking out of it, the other cases will never be reached. Try this instead:
case 1: JOptionPane.showMessageDialog(null,"c=a+b"); break;
case 2: JOptionPane.showMessageDialog(null,"c=a/b"); break;
case 3: JOptionPane.showMessageDialog(null,"c=a*b"); break;
case 4: JOptionPane.showMessageDialog(null,"c=a-b"); break;
default: JOptionPane.showMessageDialog(null,"fail"); break;
Your code does not show a while loop anywhere. Perhaps you can update with the code you attempted.
switch (num)
{
case 1:
while(!your condition)
{
JOptionPane.showMessageDialog(null,"c=a+b");
}
break;
case 2: JOptionPane.showMessageDialog(null,"c=a/b"); break;
case 3: JOptionPane.showMessageDialog(null,"c=a*b"); break;
case 4: JOptionPane.showMessageDialog(null,"c=a-b"); break;
default: JOptionPane.showMessageDialog(null,"fail"); break;
}
Retype the code:
// prompt and read first number from user
String no = JOptionPane.showInputDialog(null, "Enter the number");
int num = Integer.parseInt(no); //convert string to number
while (num<=4)
{
if
switch (num)
{
//display result
case 1: JOptionPane.showMessageDialog(null,"c=a+b"); break;
case 2: JOptionPane.showMessageDialog(null,"c=a/b"); break;
case 3: JOptionPane.showMessageDialog(null,"c=a*b"); break;
case 4: JOptionPane.showMessageDialog(null,"c=a-b"); break;
default: JOptionPane.showMessageDialog(null,"fail"); continue;
}
}// end method main
}// end class abc

Categories

Resources