I am trying to write a method that takes a single int parameter that is the numeric month and returns the number of days in the given month. So, a parameter of 1 would return 31 since there are 31 days in January and a parameter of 2 would return 28 since there are 28 days in February.
Here's what I have so far:
public static void daysInMonth(int month) {
if (month == 1||3||5||7||8||10||12)
System.out.println("31");
else if (month == 4||6||9||11)
System.out.println("30");
else if (month == 2)
System.out.println("28");
I keep getting the error message "operator || cannot be applied to boolean,int." Can anyone help me figure out what to do?
You want something like this:
if ( (month == 1) || (month == 3) || (month == 5) || (month == 7)
|| (month == 8) || (month == 10)
You can avoid any switch or if/else statements with the new Java 1.8 time API using java.time.Month:
public static int daysInMonth(int month) {
return Month.of(month).minLength();
}
You can use the || operator on a boolean expression :
if (month == 1 || month == 3 || month == 5) {
// do something ...
}
|| will result into boolean and then boolean || int is not valid action
what you need is
month == 1 || month == 3 || ...
or a Map<Integer, Integer> monthNumberToMaxDaysMap
also this way you don't have leap year scenario covered, it is suitable to re-use already solved problem
public static void daysInMonth(int month) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, month -1);
return cal.getActualMaximum(Calendar.DAY_OF_MONTH)
}
above method only considers current year, you could leverage it to pass year as well
Related
I'm supposed to make code that shows the next day, and this works except for the months that end in 31. For example, when I enter 3/31/2000, it gives me 4/2/2000 and skips the first day? I'm not sure why?
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lab53;
import java.util.Scanner;
/**
*
* #author Owner
*/
public class Lab53 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner keyboardInput = new Scanner(System.in);
int year, month, day;
System.out.println("Enter year/month/day");
year = keyboardInput.nextInt();
month = keyboardInput.nextInt();
day = keyboardInput.nextInt();
if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12))
{
day=thirtyOneDaysMonth(day);
if(day==1 && month==12){
++year;
month=1;
}
else if(day==1 && month!=12)
++month;
}
if ((month==2 || month == 4 || month == 6 || month == 9 || month == 11))
{
day=thirtyDaysMonth(day);
if(month==2 && isLeapYear(year))
{
if(day>29)
{
++month;
day=1;
}
}
else if( day>28 && month==2)
{
++month;
day=1;
}
else
{
if(day==1)
{
++month;
day=1;
}
}
}
System.out.println("The next date is:"+ month + "/" + day + "/" + year);
}
public static int thirtyOneDaysMonth(int day)
{
if(day==31)
day=1;
else
++day;
return day;
}
public static int thirtyDaysMonth(int day)
{
if(day==30)
day=1;
else
++day;
return day;
}
public static boolean isLeapYear(int year)
{
if((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)))
return true;
else
return false;
}
}
Change if ((month==2 || month == 4 || month == 6 || month == 9 || month == 11)) to else if ((month==2 || month == 4 || month == 6 || month == 9 || month == 11)).
On a day = 31 you're updating the month in your if statement. Then you leave the if but then enter your next if statement that handles months with 30 days. Your code then increments the day again.
Because after the first if has increased 3/31/2000 to 4/1/2000 the second if is evaluated which will again increase the day. Make the second if an else if instead.
In the case of month==3 and day==31, day is bumped back to 1 by
day=thirtyOneDaysMonth(day);
then the month is bumped up by
else if(day==1 && month!=12)
++month;
then the next if statement is true because now month == 4
if ((month==2 || month == 4 || month == 6 || month == 9 || month == 11))
connecting it to the previous if statement with an else if will fix the issue
else if ((month==2 || month == 4 || month == 6 || month == 9 || month == 11))
So I've been assigned a problem in my intro to programming class. I did a little research into a way to accomplish this problem and I am able to compile with no errors however one of the stipulations is that I must return a String. This is where I run my head into a brick wall. I've tried a few means to fix the issue but I'm hoping someone here can spot the issue that I've been pulling my hair out over.
public class TellSeason {
public static void main(String[] args) {
season(5 , 12);
}
public static String season(int month , int day) {
if ((month == 9 && day >=16)
|| month == 10
|| month == 11
|| (month == 12 && day <=15)) {
return ("Fall");
}
else if ((month == 12 && day >=16)
|| month == 1
|| month == 2
||(month == 3 && day <=15)) {
return ("Winter");
}
else if ((month == 3 && day >=16)
|| month == 4
|| month == 5
||(month == 6 && day <=15)) {
return ("Spring");
}
else {
return("Summer");
}
}
}
Something like this?
public static void main(String[] args){
System.out.println(season(5 , 12));
}
One more hint - you can compare month and day together
int idx = month * 100 + day;
if (idx <= 315 || idx >= 1216)
return ("Winter");
if (idx >= 916)
return ("Fall");
if (idx >= 616)
return("Summer");
//if (idx >= 316)
return ("Spring");
Two things, first you are not doing anything with the result of your method. Basically, you just call season in your main method, and do nothing with the result.
Secondly, look at the method signature of your main method. It explicitly states that main have the return type void. Which means, this method can't return anything. You can provide a exit code, by using System.exit(), however, this is limited to integer return codes.
I strongly suspect that all you are really after, is the ability to print your result to the console. That is,
System.out.println(season(5,12));
If you want to return anything from your main, it is impossible.
But if you want to display your result, System.out.println is your method
This question already has answers here:
Variables might not have been initialized
(3 answers)
Closed 8 years ago.
Doing some Java practice at home and I keep getting an error with this code.
I want to make a program which tells the season of a month that has been entered (in numerical form) but if the number is greater than 12, it should tell us that the month entered is invalid.
import java.util.Scanner;
class SeasonInput {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a month (in numbered form)");
String monthentered = input.nextLine();
int month = Integer.valueOf(monthentered);
String season;
if(month <13) {
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
System.out.println("The season that occurs during that month is " + season);
}
else
System.out.println("Enter a valid month");
}
}
It's a valid error, in your last else you don't set String season.
String season = null; // <-- give it a null. the error will go away.
You have cases where you don't initialize season.
This is what the compiler is complaining about.
Noob here so bear with me..I was working on a Java program that takes the users input from the JoptionPane, and uses a set of if-else statements to verify the date while considering the leap years. The problem I seem to be having when it runs is that it validates dates that aren't possible. For example, 2/29/2014, it says it's a valid date, but in reality it isn't.
Insight on this issue would be highly appreciated.
import java.util.Arrays;
import javax.swing.JOptionPane;
public class vaildDate {
public static void main(String[] args) {
// TODO Auto-generated method stub
int month, day, year;
String userInput = JOptionPane.showInputDialog("Enter a valid date in mm/dd/yyyy format: ");
String [] date = userInput.split("/");
String mm = date[0];
String dd = date [1];
String yyyy = date [2];
month = Integer.parseInt(mm);
day = Integer.parseInt(dd);
year = Integer.parseInt(yyyy);
System.out.println(mm+dd+yyyy);
boolean validLeapYear;
boolean validDate;
if(month>=1 && month <=12&& day>=1 && day<=31)
{
if(month == 4 || month == 9 || month == 6 || month == 11 && day <= 30)
{
validDate = true;
}
if(( month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 11 || month == 12) && (day <= 31))
{
validDate = true;
}
else{
validDate =false;
}
if((year % 400 == 0 ) || (year % 4 == 0) && (year % 100 != 0))
{
validLeapYear = true;
}
if ((month == 2 && day == 29) && (validLeapYear = false ))
{
validDate = false;
}
if((month == 2 && day <= 29) && (validLeapYear = true ))
{
validDate = true;
}
if(validDate = true)
{
JOptionPane.showMessageDialog(null, month +"/"+day+"/"+year+" is a valid date");
}
else if(validDate = false) {
JOptionPane.showMessageDialog(null,"Your date is invalid");
}
}
}
}
Instead of equating booleans your are assigning the values which return the results of your assignment.
For example:
if (validDate = true)
The above statement would return true. Instead, in all your boolean checks just validate the boolean value as is.
if (validDate)
To remove the compiler errors, you can initialize your 2 boolean vars to false.
You changed code would look something like:
public static void main(String[] args) {
// TODO Auto-generated method stub
int month, day, year;
String userInput = JOptionPane
.showInputDialog("Enter a valid date in mm/dd/yyyy format: ");
String[] date = userInput.split("/");
String mm = date[0];
String dd = date[1];
String yyyy = date[2];
month = Integer.parseInt(mm);
day = Integer.parseInt(dd);
year = Integer.parseInt(yyyy);
System.out.println(mm + dd + yyyy);
boolean validLeapYear = false;
boolean validDate = false;
if (month >= 1 && month <= 12 && day >= 1 && day <= 31) {
if (month == 4 || month == 9 || month == 6 || month == 11
&& day <= 30) {
validDate = true;
}
if ((month == 1 || month == 3 || month == 5 || month == 7
|| month == 8 || month == 11 || month == 12)
&& (day <= 31)) {
validDate = true;
} else {
validDate = false;
}
if ((year % 400 == 0) || (year % 4 == 0) && (year % 100 != 0)) {
validLeapYear = true;
}
if ((month == 2 && day == 29) && (!validLeapYear)) {
validDate = false;
}
if ((month == 2 && day <= 29) && (validLeapYear)) {
validDate = true;
}
if (validDate) {
JOptionPane.showMessageDialog(null, month + "/" + day + "/"
+ year + " is a valid date");
}
else if (!validDate) {
JOptionPane.showMessageDialog(null, "Your date is invalid");
}
}
}
A quick search on Google shows there are easier ways to validate a date. Please see this one:
http://www.mkyong.com/java/how-to-check-if-date-is-valid-in-java/
It uses the date parse and catches the exception if the date is not valid (cannot be parsed).
If you want to stick with your algorithm, I suggest to use an IDE like Eclipse and debug set by step while keeping a look on the value of your variables. You clearly have an algorithm problem, which will become obvious while debugging.
Hope that helps.
I am a beginner in java and i am doing some practiceit questions to brush up on my java skills.
Write a method named season that takes two integers as parameters representing a month and day and that returns a String indicating the season for that month and day. Assume that months are specified as an integer between 1 and 12 (1 for January, 2 for February, and so on) and that the day of the month is a number between 1 and 31.
If the date falls between 12/16 and 3/15, you should return "Winter". If the date falls between 3/16 and 6/15, you should return "Spring". If the date falls between 6/16 and 9/15, you should return "Summer". And if the date falls between 9/16 and 12/15, you should return "Fall".
public static String season(int month,int day){
if(month>=9 && month<=12 && day==15||day==16){
return "Fall";
}
else if (month>=4 && month<=6 && day==16||day==15){
return "Spring";
}
else if (month>=6 && month<=9 && day==16||day==15){
return "Summer";
}
else {
return"Winter";
}
}
But i'm not getting the output.But it seems right to me.Anyone can tell me where did i go wrong?
|| has lower precendence than && and your conditions don't look correct - you probably wanted to write something like:
if((month == 9 && day >= 16) //September, on or after the 16th
|| month == 10 //or October
|| month == 11 //or November
|| (month == 12 && day <=15)) { //or December, but before or on the 15th
return "Fall";
}
(same comment for the other conditions)
You could make it shorter by using a little hack, but readability is maybe not as good (debatable):
int mdd = month * 100 + day; //date in MDD format, for example 507 for May 7th
if (mdd >= 916 && mdd <= 1215) {
return "Fall";
}
You should try to write something like this:
if((month>9 && month<12) || (month==9 && day>=16) || (month==12 && day<=15)){
return "Fall";
} else if
...
}
The precedences are important, also, but you have to think over what you really want to achieve, and build your expression according to that.
if(month>=9 && month<=12 && (day==15||day==16)){
return "Fall";
}
This issue with this is that only the 15th and 16th of months 9-12 are considered the winter.
Solution
If it were up to me, I would re-factor the if-else tree to first check for months, then check the days. So for example:
if(month>=9 && month<=12)
{
// Some special cases.
if((month == 9 && day < 15) || (month == 12 && day > 16))
{
// It isn't fall.
}
else
{
// It is fall.
}
}
This runs just fine. You had some minow mistakes I corrected
public static String season(int month,int day){
if((month>=9 && month<=12) && (day==15||day==16))
return "Fall";
else{
if ((month>=4 && month<=6) && (day==16||day==15))
return "Spring";
else{
if ((month>=6 && month<=9) && (day==16||day==15))
return "Summer";
else
return"Winter";
}
}
}