About The switch Statement in Java - 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

Related

change this code from if, else to Switch case

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!");
}

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;
}

Switch Statement and Case

I am making code for my CPSC class and I have to print up to a case number that is set for the int. When I enter "2", the code prints "two potato" eight times instead of "One potato, two potato".
Here is my code I have:
public class Potato {
public Potato() {
}
public void count(int c) {
for (int i = 0; i < 8; i++) {
switch (c % 8) {
case 1: System.out.println("One potato"); break;
case 2: System.out.println("two potato"); break;
case 3: System.out.println("three potato"); break;
case 4: System.out.println("four..."); break;
case 5: System.out.println("five potato"); break;
case 6: System.out.println("six potato"); break;
case 7: System.out.println("seven potato"); break;
case 8: System.out.println("more!"); break;
default: break;
}
}
}
}
I think my problem is my for-loop, not too sure though, since I am here asking for help. Thanks in advance!
It is because c % 8 (2 % 8 = 2), so in every loop it will execute case 2 and prints two potato. You could use i % 8 instead.
This should do the trick. As others have said, you should use i%8. However, for this to work you should also start with i=1 since 0%8 = 0. And your case 8 should be changed to case 0.
for (int i = 1; i <= c; i++) {
switch (i % 8) {
case 1: System.out.println("One potato"); break;
case 2: System.out.println("two potato"); break;
case 3: System.out.println("three potato"); break;
case 4: System.out.println("four..."); break;
case 5: System.out.println("five potato"); break;
case 6: System.out.println("six potato"); break;
case 7: System.out.println("seven potato"); break;
case 0: System.out.println("more!"); break;
default: break;
}
}
This code is... peculiar:
The main problem is that you are not using the i variable that is incremented at the for loop. Instead, you are using c variable:
switch (c % 8)
Should be:
switch (i % 8)
You don't need the case 8 since there is no way that i % 8 result in 8. And, looks like you don't need c variable at all.

Need help in understanding this switch code - Days of the months

I am learning Java at the moment and I have some problems understanding the use of switch here. I would really appreciate it if someone could explain it simple to me.
So here's the code:
public class SwitchDemo2 {
public static void main(String[] args) {
int month=3;
int year=2000;
int NumDays=0;
switch(month) {
case 1: case 3: case 5: case 7: case 8: case 10:
case 12: NumDays=31; break;
case 4: case 6: case 9: case 11: NumDays=30;
break;
case 2: if ( ( (year%4 == 0) && !(year%100==0) ) ||
(year%400==0))
NumDays=29;
else NumDays=28;
break;
default: System.out.println("Invalid month.");
break;}
System.out.println("Number of Days= "+NumDays);
}}
What I don't understand is the definiton after case 2. "year%4==0" - alright, that makes sense, that's a leap year, but what about !(year%100==0) or (year%400==0) ? Why do we use that?
Thanks in advance!
By the definition of leap year:
if year is divisible by 400 then is_leap_year
else if year is divisible by 100 then not_leap_year
else if year is divisible by 4 then is_leap_year
else not_leap_year

why is the wrong "case" being executed after "default" in a switch statement

How is it possible that the output is 1002,why is the last case being executed despite having a mismatch?
public class Main {
public static void main(String[] args) {
int i=0,j=0;
switch (i) {
case 2 : j++;
default: j+=2;
case 15 : j+=1000;
}
System.out.println("j="+j);
}
}
FALLTHROUGH:
Another point of interest is the break statement. Each break statement
terminates the enclosing switch statement. Control flow continues with
the first statement following the switch block. The break statements
are necessary because without them, statements in switch blocks fall
through: All statements after the matching case label are executed in
sequence, regardless of the expression of subsequent case labels,
until a break statement is encountered.
Your code should be:
case 2 : j++; break;
case 4: j+=10; break;
default: j+=2; break;
case 15: j+=1000;
}
FROM DOCS
public class Example{
public static void main(String[] args) {
java.util.ArrayList<String> futureMonths =
new java.util.ArrayList<String>();
int month = 8;
switch (month) {
case 1: futureMonths.add("January");
case 2: futureMonths.add("February");
case 3: futureMonths.add("March");
case 4: futureMonths.add("April");
case 5: futureMonths.add("May");
case 6: futureMonths.add("June");
case 7: futureMonths.add("July");
case 8: futureMonths.add("August");
case 9: futureMonths.add("September");
case 10: futureMonths.add("October");
case 11: futureMonths.add("November");
case 12: futureMonths.add("December");
default: break;
}
if (futureMonths.isEmpty()) {
System.out.println("Invalid month number");
} else {
for (String monthName : futureMonths) {
System.out.println(monthName);
}
}
}
}
This is the output from the code:
August
September
October
November
December
You have to break at the end of the case blocks. Otherwise all subsequent cases will be also executed.
public class Main {
public static void main(String[] args) {
System.out.println("Hello World!");
int i=0,j=0;
switch (i){
case 2 : j++; break;
case 4: j+=10; break;
case 15 : j+=1000; break;
default: j+=2;
}
System.out.println("j="+j);
}
}
Because you are missing break;
and if I understand your confusion, The order of default doesn't matter. In below case,
int i=15,j=0;
switch (i){
case 2 :
j++;
break;
case 4:
j+=10;
break;
default:
j+=2;
break;
case 15 :
j+=1000;
break;
}
j will be having value 1000 even if default was before case 15
you don't have the 'break' keyword specified in each of your cases.
Should be like this:
switch (i){
case 2 :
j++;
break;
case 4:
j+=10;
break;
case 15 :
j+=1000;
break;
default:
j+=2;
break;
}
In this case case 2 and case 4 are not execute but default and case 15 are so the answer is 1002. Please put break statement for desired result.
Hope this helps.

Categories

Resources