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.
Related
is it considered bad practice to write a switch case statement with a comma such as this:
switch(name)
{
case 'a', 'A' :
break;
}
Rather than
switch(name)
{
case 'a':
case 'A':
break;
}
Just curious as my code seems to run fine either way but I want to get into the habit of using the proper/most accepted way.
It's not bad practice. In fact, it's considered concise and time-efficient.
Take a look at the following code that you have
switch(name){
case 'a', 'A' :
break;
}
The equivalent without using commas would be:
switch(name){
case 'a':
break;
case 'A':
break;
}
And the if-else equivalent would be:
if(name=='a'){
//Do something
}else if(name=='A'){
//Do something
}
Of these, the first example took a mere 36 characters to type. The latter took 49, and the last one took 37 characters.
Moral? Using the comma is definitely more concise and time-efficient that using two cases with a single result. Even the if statements would be more concise.
CheckStyle, the defacto standard for java style, has no check for this.
Do whatever is easiest to read.
I would say though use only one style or the other in any given switch statement.
From JavaDocs:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
class SwitchDemo2 {
public static void main(String[] args) {
int month = 2;
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);
}
}
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;
}
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
The following code should print whether intenger value is odd or even with fall through switch statement and for statements
for(int i=2; i<=10; i+=2)
{
switch(i)
{
case 1:
{System.out.printf("\nNot printing odd numbers");}
case 2:
System.out.printf("\n %d is an even number.", i);
//case 3:
//case 4:
}//end switch
}//end for
Change i+=2 to i++ and i+=2 will give you value of i as 2,4,6,8,10 which means only even numbers.
switch(i%2)
{
case 0:
//even number
break;
case 1:
//Odd Number
break;
}
There is no need given your for loop,
for(int i=2; i<=10; i+=2)
i will not be odd. Based on your switch and problem statement I think you wanted,
for(int i=1; i<=10; i++) {
switch(i) {
case 2: case 4: case 6: case 8: case 10:
System.out.printf("\n %d is an even number.", i);
break;
default:
System.out.printf("\nNot printing odd numbers");
}
}
I believe a fall-through switch should look like this. I have ommitted your outer for loop for simplicity.
switch (i)
{
case 1:
case 3:
case 5:
case 7:
case 9:
System.out.printf("\nNot printing odd numbers");
break;
case 2:
case 4:
case 6:
case 8:
System.out.printf("\n %d is an even number.", i);
break;
}
You essentially Fallthrough some cases (all odd numbers and all even numbers). Hence the term. You can read more about fallthrough here.
for (int i = 2; i <= 10; i++) {
switch (i % 2) {
case 0: // even number
System.out.printf("\n %d is an even number.", i);
break;
case 1: // odd number
System.out.printf("\nNot printing odd numbers");
break;
}// end switch
}// end for
Try this
for (int i = 2; i <= 10; i++) {
switch (i % 2) {
case 0:
System.out.printf("\n%d is an even number.", i);
break;
case 1:
System.out.printf("\nNot printing odd numbers");
break;
}// end switch
}// end for
}
nt num=10;//any number you want
nt last=num%10;
switch(last)
{
case 0:
case 2:
case 4:
case 6:
case 8:
System.out.println("numbet is even" +num) ;
break ;
default :
System.out.println("number is odd" +num)
}
//end of switch block
//odd or even using fall through language java
//GAGAN GANJWAR
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.