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
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);
}
}
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
I'm pretty new to Java, and coding in general. In my class we need the user to input the month (1-12) and a day (1-30) and we determine on a set date (june 15 to sept 30th) if it is or is not monsoon season. I'm trying to use a if else statement in a switch to say that anytime before june 15 is not monsoon season but my code keeps showing both if and else statement. Any help is welcomed, thank you!
import java.util.*;
public class Monsoon
{ public static void main (String[]args)
{
Scanner kb = new Scanner (System.in);
// Prompt the user to enter month & Day
System.out.print("Please enter a month(1-12) and day (1-31): " );
int month = kb.nextInt();
int day = kb.nextInt();
// using a switch statement to show months
switch (month){
case 1:
System.out.println("is NOT monsoon season");
break;
case 2:
System.out.println("is NOT monsoon season");
break;
case 3:
System.out.println("is NOT monsoon season");
break;
case 4:
System.out.println("is NOT monsoon season");
break;
case 5:
System.out.println("is NOT monsoon season");
break;
case 6:
System.out.println("“is monsoon season");
// use if else statement so user knows that before june 15 is not monsoon season
if (day>=15)
System.out.print("it is monsoon season");
else
System.out.print("it is not monsoon season");
break;
case 7:
System.out.println("“is monsoon season");
break;
case 8:
System.out.println("“is monsoon season");
break;
case 9:
System.out.println("“is monsoon season");
break;
case 10:
System.out.println("is NOT monsoon season");
break;
case 11:
System.out.println("is NOT monsoon season");
break;
case 12:
System.out.println("is NOT monsoon season");
break;
default: System.out.println("not valid");
break;
}
}
}
Repetition is bad. You can do it like this, utilizing the fall-through feature of the switch-case:
boolean isMonsoon;
switch (month) {
case 7:
case 8:
case 9:
isMonsoon = true;
break;
case 1:
case 2:
case 3:
case 4:
case 5:
case 10:
case 11:
case 12:
isMonsoon = false;
break;
case 6:
// use if else statement so user knows that before june 15 is not monsoon season
if (day >= 15)
isMonsoon = true;
else
isMonsoon = false;
break;
default:
System.out.println("not valid");
break;
}
if (isMonsoon)
System.out.println("is monsoon season");
else
System.out.println("is NOT monsoon season");
Or, since the monsoon season is a range, using comparison operators is probably more suitable than a switch-case:
if ((month >= 7 && month < 10) || (month == 6 && day >= 15))
System.out.println("is monsoon season");
else
System.out.println("is NOT monsoon season");
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.
I only need help with the input part. If the user inputs a number I need the program to read and output a case that equals the number that was input.
//This program will display the months of the year
public class MonthsOfTheYear {
public static void main(String[] args)
throws java.io.IOException{
int month;
System.out.println("Please enter a Month Number: ");
month = (int) System.in.read(); //Get an integer
switch (month) {
case 1: System.out.println("January");
break;
case 2: System.out.println("February");
break;
case 3: System.out.println("March");
break;
case 4: System.out.println("April");
break;
case 5: System.out.println("May");
break;
case 6: System.out.println("June");
break;
case 7: System.out.println("July");
break;
case 8: System.out.println("August");
break;
case 9: System.out.println("September");
break;
case 10: System.out.println("October");
break;
case 11: System.out.println("November");
break;
case 12: System.out.println("December");
break;
default: System.out.println("Invalid Month");
break;
}
System.out.println();
}
}
Try using the Console class instead: http://docs.oracle.com/javase/6/docs/api/java/io/Console.html to obtain user input, then convert the String to a number with Integer.parseInt(String)
Also, be aware that the next version of Java (8) will support Strings in case blocks.
class vehicle
{
int passengers;
int fuelcap;
int mpg;
}
import java.io.*;
class Vehicle_Demo
{
public static void main (String args[]) throws java.io.IOException
{
vehicle obj1 = new vehicle();
obj1.passengers=12;
obj1.fuelcap=9;
obj1.mpg=78;
System.out.println(obj1.passengers, obj1.fuelcap, obj1.mpg);
}
}
You can use Scanner to read your System.in
Scanner input = new Scanner(System.in);
month = input.nextInt();
Output:
Please enter a Month Number:
1
January
See related
Edit:
as noahz pointed out there is a Console class that covers the same functionality. For an idea of the difference between the two, read this.
Try to use TextIO Input Functions
This is better than scanner input
You need to compile TextIO.java fist as a prerequisite so that TextIO.class must be found in the same folder.
use this input function instead:
month = TextIO.getChar();
Please let me know if you have problems on this method.
Thanks!
Correct me if I'm wrong, but I'm pretty sure it will still work with "system.in.read". You're switch cases do not have single quotes around the input you want to be processed. If you want case one to be run when you type '1' your case should be case '1', not case 1.
There problem here was Java have cast a character to an integer, therefore you get an ASCII value.
For instance, when you type 5 you've got 53 in ASCII. Check it taking the variable value in System.out.println();
I've tried to solve that changing month to a char type and then passing a char value to the switch control. But the problem is, getting System.in.read(); method you just can get a single character. At last you just can select between 1 to 9.
I suspect the solution is using a buffer reader. Until then, I leave you here my code:
public class MonthsOfTheYear {
public static void main(String[] args)
throws java.io.IOException{
char month;
System.out.println("Please enter a Month Number: ");
month = (char) System.in.read(); //Get an integer
//System.out.println("Actual value of :" + month);
switch (month) {
case '1': System.out.println("January");
break;
case '2': System.out.println("February");
break;
case '3': System.out.println("March");
break;
case '4': System.out.println("April");
break;
case '5': System.out.println("May");
break;
case '6': System.out.println("June");
break;
case '7': System.out.println("July");
break;
case '8': System.out.println("August");
break;
case '9': System.out.println("September");
break;
/*case '10': System.out.println("October");
break;
case '11': System.out.println("November");
break;
case '12': System.out.println("December");
break;*/
default: System.out.println("Invalid Month");
break;
}
System.out.println();
}
}