Java finding the next leap year - java

How do I find the next leap year if the given input isn't a leap year?
A year is considered a leap year when it is either:
divisible by 4, but not 100 or
divisible by both 4, 100, and 400 at the same time
Input:
A single line containing a number that represents a year, here 1702.
Output:
The next soonest leap year if the input is not a leap year. Otherwise, output "Leap year".
The next leap year is 1704
Heres my code:
When I input 1702 nothing shows but if it's 1700 it works. If ever you can help pls only use if else or while since these two are the only allowed for it to run.
import java.util.Scanner;
class Main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int year = input.nextInt();
int leap = 0;
if (year % 400 == 0) {
System.out.print("Leap year");
} else if (year % 100 == 0) {
leap += 4;
year += leap;
System.out.print("The next leap year is ");
System.out.print(year);
} else if (year % 4 == 0) {
System.out.print("Leap year");
}
input.close();
}
}

tl;dr short solution with java.time:
Java 8+ provide the package java.time which has a class Year which provides a method to determine if that very year was/is/will be a leap year, that is Year.isLeap().
You could use it to get your desired result, maybe like in the following example:
public static void main(String[] args) {
// hard-coded example number
int numericalYear = 1702;
// create the year from the number given
Year year = Year.of(numericalYear);
// check if that year is leap
if (year.isLeap()) {
System.out.println("Leap Year");
} else {
// of find the next one by adding 1 year and checking again
while (!year.isLeap()) year = year.plusYears(1);
// print the next one
System.out.println("Next leap year is " + year);
}
}
This example has an output of
Next leap year is 1704

The major part of the main() is an if-statement with three branches. I think the most difficulties you have is you mixed the part to determine a leap year, and the part to control the workflow.
The workflow of your program is:
Take an user input
Check if this is a leap year
Print the response according to step 2
The logic to determine a leap year is:
divisible by 4, but not 100 or
divisible by both 4, 100, and 400 at the same time
You could try to isolate these two area with two different piece of code. Take one step at a time. Then things will become less complex. You can simplify your if from three to two branches. Since the year is either a leap or not, no other possibility. If it is leap year, print the year. Else, print next leap year. Only two cases.
In order to check whether a year leap year or not, obviously you need an algorithms. You can decouple the algorithms into a separate function. This way you can isolate the leap year logic with your workflow.
Example
import java.util.Scanner;
public class Main{
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int year = input.nextInt();
// base cycle is 4 year
final int leapCycle = 4;
if (isLeapYear(year)) {
System.out.print("Leap year");
} else {
// complete the year with next cycle
year += leapCycle - (year % leapCycle);
// the next maybe not a leap year e.g. 1800, 1900
if (!isLeapYear(year)) {
// then advance it with one more cycle
year += leapCycle;
}
System.out.print("The next leap year is ");
System.out.print(year);
}
input.close();
}
private static boolean isLeapYear(int year) {
if (year % 4 == 0) {
if (year % 100 == 0) {
return year % 400 == 0;
} else {
return true;
}
}
return false;
}
}
Test cases
1700
The next leap year is 1704
1702
The next leap year is 1704
1799
The next leap year is 1804
1800
The next leap year is 1804
1999
The next leap year is 2000
2000
Leap year
2001
The next leap year is 2004

Related

How do I print out a calendar month in console?

I have an assignment for a class I'm taking in which I have to make a Java console application, and it involves asking the user for a date, parsing that date, and working out what day of the month that date starts on. I have to then print out a calendar to look like this:
Calendar for September 2016
Su Mo Tu We Th Fr Sa
- - - - 1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 -
I have the date, I have the number of the day that the date starts on, (eg. Day= 1 (Monday), Day= 2(Tuesday), etc.)
Now, I can use a very messy looking switch statement with nested if statements that says, depending on the value of Day, and the number of days in that month, print out this pre-made calendar, and I can just pre-make a calendar for every eventual combination of Day and number of days in that month. But I don't want to do that, and I can't figure out an easier way of doing it. Has anybody got any ideas of a tidier, more succinct way of doing it? Would it be something involving 2d arrays?
PS. I'm not allowed to use any date-based library classes available in Java.
well you can use this if you change your mind
public static void main(String args [])
{
// type MM yyyy
Scanner in = new Scanner(System.in);
System.out.print("Enter month and year: MM yyyy ");
int month = in.nextInt();
int year = in.nextInt();
in.close();
// checks valid month
try {
if (month < 1 || month > 12)
throw new Exception("Invalid index for month: " + month);
printCalendarMonthYear(month, year);}
catch (Exception e) {
System.err.println(e.getMessage());
}
}
private static void printCalendarMonthYear(int month, int year) {
Calendar cal = new GregorianCalendar();
cal.clear();
cal.set(year, month - 1, 1); // setting the calendar to the month and year provided as parameters
System.out.println("Calendar for "+ cal.getDisplayName(Calendar.MONTH, Calendar.LONG,
Locale.US) + " " + cal.get(Calendar.YEAR));//to print Calendar for month and year
int firstWeekdayOfMonth = cal.get(Calendar.DAY_OF_WEEK);//which weekday was the first in month
int numberOfMonthDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH); //lengh of days in a month
printCalendar(numberOfMonthDays, firstWeekdayOfMonth);
}
private static void printCalendar(int numberOfMonthDays, int firstWeekdayOfMonth) {
int weekdayIndex = 0;
System.out.println("Su MO Tu We Th Fr Sa"); // The order of days depends on your calendar
for (int day = 1; day < firstWeekdayOfMonth; day++) {
System.out.print(" "); //this loop to print the first day in his correct place
weekdayIndex++;
}
for (int day = 1; day <= numberOfMonthDays; day++) {
if (day<10) // this is just for better visialising because unit number take less space of course than 2
System.out.print(day+" ");
else System.out.print(day);
weekdayIndex++;
if (weekdayIndex == 7) {
weekdayIndex = 0;
System.out.println();
} else {
System.out.print(" ");
}}}

.class expected error when calling boolean method [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am getting an error when trying to call a boolean method from another class. I have tried editing the way I am calling the method, but none have worked so far. I'm posting the code I had for both classes for the clearest error message i got which was the ".class" expected error.
public class Date
{
public int Day;
public int Month;
public int Year;
public Date(int myDay, int myMonth, int myYear){
Month = myMonth;
Day = myDay;
Year = myYear;
}
public int daysIs(){
return Day;
}
public int monthIs(){
return Month;
}
public int yearIs(){
return Year;
}
public boolean isLeapYear(int Year){
if (Year % 4 != 0){
return false;
}else if (Year % 400 == 0) {
return true;
}else if (Year % 100 == 0){
return false;
}else {
return true;
}
}
Date mydate = new Date(Day, Month, Year);
}
For the first class here it compiles with no errors. The method I am trying to call is the isLeapYear method near the end. My second class always has some kind of error when I try to call the method.
import javax.swing.JOptionPane;
public class DateJDialog
{
public static void main(String[]args)
{
String input;
int Day;
int Month;
int Year;
//prompt the day
input = JOptionPane.showInputDialog("Please enter the 2 digit day of the month: ");
Day = Integer.parseInt(input);
//prompt the month
input = JOptionPane.showInputDialog("Please enter the 2 digit month of the year: ");
Month = Integer.parseInt(input);
//prompt the year
input = JOptionPane.showInputDialog("Please enter the 4 digit year: ");
Year = Integer.parseInt(input);
Date inputDate = new Date(Day,Month,Year);
if( inputDate.isLeapYear(int Year)= false){
JOptionPane.showMessageDialog(null,"The given year was NOT a Leap Year.");
}else {
JOptionPane.showMessageDialog(null,"The given year WAS a Leap Year.");
}
}
}
The errors always happen on the first line of the if statement near the end.
Try to write this line of if condition.
if (inputDate.isLeapYear(int Year)= false) {...}
Like this:
if (!inputDate.isLeapYear(2015)) {
You don't specify a data type of a parameter when you call a method. Also, = is an assigning operator, in conditions we use a comparing operator ==.
There is no need of comparing a boolean value to another boolean value, so == is pointless in this case.
Your thinking too hard, you should take it simple when programming. You don't need the type when calling a method, only do this when you declare it.

Cost Calculator

My code needs to calculate the cost of ISP service via 3 different questions.
choice of package (1,2,3)
Which month it is: (1-12)
How many hours used:(x)
I broke the months into 3 separate arrays. One for Feb. with 28 days, one for months with 30 days and one with months that have 31 days. I need to check the number of hours entered and make sure that it does not exceed the amount of hours that are in whichever month they have chosen. I have started to with this:
import java.util.Scanner; //Needed for the scanner class
public class ISP_Cost_Calc
{
public static void main(String[] args)
{
String input; //To hold users input.
char selectPackage; //To hold Internet Package
double hourUsage, totalCharges, addCharges; //Variables
Scanner keyboard = new Scanner(System.in); //Create a Scanner object to collect keyboard input.
int[] twentyeightArray; //List of months with 28 days (that's what the te is for)
twentyeightArray = new int[1]; //Make room for one integer in list
twentyeightArray[0] = 2; //Set the one integer in this list to month number 2
int[] thirtyArray; //List of months with 30 days.
thirtyArray = new int[4];
thirtyArray[0] = 4;
thirtyArray[1] = 6;
thirtyArray[2] = 9;
thirtyArray[3] = 11;
int[] thiryoneArray; //List of months with 31 days.
thiryoneArray = new int[7];
thiryoneArray[0] = 1;
thiryoneArray[1] = 3;
thiryoneArray[2] = 5;
thiryoneArray[3] = 7;
thiryoneArray[4] = 8;
thiryoneArray[5] = 10;
thiryoneArray[6] = 12;
//Prompt the user to select a Internet Package.
System.out.print("Enter your plan (1, 2, 3):");
input = keyboard.nextLine();
selectPackage = input.charAt(0);
//Prompt the user for the month.
System.out.print("Enter your month number (1-12):");
input = keyboard.nextLine();
char monthNum = input.charAt(0);
//Prompt the user for how many hours used.
System.out.print("Enter your hours:");
input = keyboard.nextLine();
hourUsage = Double.parseDouble(input);
//Display pricing for selected package...
switch (selectPackage)
{
case '1':
if (hourUsage > 10)
{
addCharges = hourUsage - 10;
totalCharges = (addCharges * 2.0) + 9.95;
System.out.println("You have used " + hourUsage + " hours and your total is $" + totalCharges + " per month. ");
}
else
{
System.out.println("Your total is $9.95 per month.");
}
break;
case '2':
if (hourUsage > 20 )
{
addCharges = hourUsage - 20;
totalCharges = (addCharges * 1.0) + 13.95;
System.out.println("You have used " + hourUsage + " and your total is $" + totalCharges + " per month.");
}
else
{
System.out.println("Your total is $13.95 per month.");
}
break;
case '3':
System.out.println("Your total is $19.95 per month.");
break;
default:
System.out.println("Invalid Choice.");
}
}
}
So I just need advice with how to incorporate this into my if statements.
Thank you
Instead of using separate arrays to implement your month. You can do this:
int[] month = {31,28,31,30,31,30,31,31,30,31,30,31};
int[] monthLeapYear = {31,29,31,30,31,30,31,31,30,31,30,31};
You can check whether a given year is a leap year first, then choose the right array to use for the month. This way you only need 2 arrays - ever.
and you may have something like this to help you. I also advise you to create some methods in your implementation to modularize your program.
public static Boolean isLeapYear(int year)
{
if(year % 4 == 0 && year % 100 != 0)
return true;
return false;
}
The array is by index 0 - 11. That be can be over come by doing this:
//Let say your current month is 1-12
month[currentMonth-1]
Alternatively add 1 element to your array (so that the elements tally now):
int[] month = {0,31,28,31,30,31,30,31,31,30,31,30,31};
It may be easier if instead of using seperatre arrays for different numbers of days, you use an enum of Months which contains the number of days and the number of hours.
public enum Month {
JANUARY(31),FEBRUARY(28),MARCH(31),APRIL(30),MAY(31),JUNE(30),JULY(31),AUGUST(30),SEPTEMBER(30),OCTOBER(31),
NOVEMBER(30),DECEMBER(31);
private int hours;
private Month(int days){
hours = days*24;
}
public int getHours(){
return hours;
}
}
Using something like that would cut down on the unnecessary array use and combine everything into a single class. This would make it a lot easier to get the number of days and hours in each month.
Instead of creating multiple arrays, just use one array like:
month[0] = 31;
month[1] = 28;//what if leap year?
month[2] = 31;
//and so on
Then you could do something like:
int monthNumber = monthNum - 48;
if (hours > month[monthNumber - 1] * 24) {
//do something
} else {
//else do another thing
}
This is insane.
What is going to happen in 2016 when February will have 29 days instead of 28 days?
Stop using integers to represent hours. Use proper data types like DateTime and TimeSpan.
Get the DateTime at 00:00 of the 1st day of the selected month,
then get the DateTime at 00:00 of the 1st day of the next month,
then calculate the difference of these two to obtain a TimeSpan holding the duration of the selected month.
Then convert your hours to a TimeSpan and compare this against the duration of the selected month.
This will tell you whether the entered number of hours fits within the selected month.
To check conditions based on your months.You can use contains method of arraylist by converting array into arraylist as
Arrays.asList(your1stArray).contains(yourChar)
in your char just add the input no of the month
for eg:
switch (monthNum )
{
case '1':
if (Arrays.asList(your1stArray).contains(yourChar)){
//code goes here
}
case '1':
if (Arrays.asList(your2ndArray).contains(yourChar)){
//code goes here
}
)
)

Getting day of the week, switch statement/toString issues implementation of leap year aswell [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm working on a little project for school and my group members and I struggling with a few things in our code. We need to write code for determining the day of the week, any given date would be on, we have the code for it, and we are using a switch statement to help assign the proper day for the equation output. For instance if the equation returns 0 it is Sunday, 1 it is Monday and so on.
This is what we have so far:
*/
public class Date {
/**
* Construct a date object.
* #param year the year as integer, i.e. year 2010 is 2010.
* #param month the month as integer, i.e.
* january is 1, december is 12.
* #param dayOfMonth the day number in the month, range 1..31.
* PRECONDITION: The date parameters must represent a valid date.
*/
private int year;
private int month;
private int dayOfMonth;
public Date(int year, int month, int dayOfMonth) {
this.year = year;
this.month = month;
this.dayOfMonth = dayOfMonth;
}
public enum Weekday {
MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY,
SATURDAY, SUNDAY };
public String toString() {
String theDate = month + " " + dayOfMonth + ", " + year;
return theDate;
}
public boolean isLeapYear(){
if ((this.year % 400 == 0)|| (this.year % 100 != 0 && this.year % 4 == 0))
return true;
else return false;
/**
* Calculate the weekday that this Date object represents.
* #return the weekday of this date.
*/
public String dayOfWeek() {
int century = year/100;
int day = (dayOfMonth - month + year +(year/4) + century) %7;
Weekday i;
switch(day){
case 1:
i = Weekday.MONDAY;
System.out.println("The day of the week for this month is Monday.");
case 2:
i = Weekday.TUESDAY;
System.out.println("The day of the week for this month is Tuesday.");
case 3:
i = Weekday.WEDNESDAY;
System.out.println("The day of the week for this month is Wednesday.");
case 4:
i = Weekday.THURSDAY;
System.out.println("The day of the week for this month is Thursday.");
case 5:
i = Weekday.FRIDAY;
System.out.println("The day of the week for this month is Friday.");
case 6:
i = Weekday.SATURDAY;
System.out.println("The day of the week for this month is Saturday.");
case 0:
i = Weekday.SUNDAY;
System.out.println("The day of the week for this month is Sunday.");
}
return i.name();
}
}
We need to implement a toString() method and we are struggling to figure out what the dayOfWeek method should return. Also how should we implement our isLeapYear() method?
You are missing break; in you cases, Java executes all the subsequent case (until it finds a next break) if a matching case doesn't have a break;.
You need to initialize the i atleast with null (ideal would be to initialize with fallback day let's say the first day of week in case it doesn't go into any case)
WeekDay i = null; or WeekDay i = WeekDay.SUNDAY;
Also, you need to return (after the complete switch) i.name().

How to have int input correlate to a substring?

I am trying to write a program that takes input from a user. The enter a number 1-12 and it returns the month January-December. I have to have all the months in one long string and then use a substring to return the corresponding month.
I am very confused as to how to get an int to correlate to a substring. I would appreciate some general guidelines for doing this. I'm not looking to have the whole program done for me.
Don't use substring(). If you have a csv of month names, use split() to turn the string into an array:
String months = "January,February,etc";
int choice; // 1-12
String monthName = months.split(",")[choice - 1];
Note that java arrays are zero-based, so you must subtract 1 from a 1-12 ranged number when used as an index.
Easier to read would be:
static String[] monthNames = "January,February,etc".split("");
then in your method:
String monthName = monthNames[choice - 1];
When you get the values of the month using your substring, store it in your array of String. And then get the 1 - 12 value by their indexes + 1.
Beside using Split you can use StringTokenizer to parse your string as well.
My Code:
int i = 1;
int month = 0;
while (i == 1) {
System.out.println("Enter your number ");
Scanner input = new Scanner(System.in);
month = input.nextInt();
if (month > 13 || month < 0) {
System.out.println("your number has to be between 1 and 12");
} else {
i = 2;
}
}
List<String> monthList = new ArrayList<>();
StringTokenizer st = new StringTokenizer("January February March April"
+ " May June July August September October November December");
while (st.hasMoreTokens()) {
monthList.add(st.nextToken(" "));
}
System.out.println("the month is " + monthList.get(month - 1));
My Output:
Enter your number
333
your number has to be between 1 and 12
Enter your number
3
the month is March

Categories