I have written a program to calculate a leap year. The second part is where i have to print the number of years to the next leap year if the year is not a leap year.
For 2097 ,the output shows 3 years untill next leap but its supposed to be 7 years. I think i have made a mistake with the code in the last line. Please help me out.
This is my code so far.
public static void main(String[] args) {
// TODO code application logic here
int year = 2093;
if((year%4==0) && year%100!=0){
System.out.println(year + " is a leap year.");
}
else if ((year%4==0) && (year%100==0)&& (year%400==0)) {
System.out.println(year + " is a leap year.");
}
else {
System.out.println(year + " is not a leap year");
System.out.println(4-(year%4) + " years untill next leap year");
}
Your leap year determination appears correct. However, you are calculating the next leap year based on the incorrect "every 4 years is a leap year" rule with this expression:
4-(year%4)
You can find the next leap year by the following:
Start with the next year after year. Use the same logic you have already written to determine if it's a leap year.
If it's not, keep incrementing that "next year" value until you do find a leap year.
You will find it useful to place your if logic in a separate method to avoid the repetition of code and logic.
Main code:
int year = 2093;
if (isLeapYear(year) {
System.out.println(year + " is a leap year");
} else {
int moreYears = nextLeapYear(year) - year;
System.out.println(moreYears + " more years until next leap year");
}
Check if a year is a leap year:
public boolean isLeapYear(int year)
{
if (year % 4 != 0)
return false;
else if (year % 100 != 0)
return true;
else if (year % 400 != 0)
return false;
else
return true;
}
Get next leap year:
public int nextLeapYear(int year)
{
while( !isLearpYear(year) )
year++;
return year;
}
Related
I wrote a simple program that is supposed to display whether if a user inputted int is a leap year or not, and if so what leap year is it.
During running of the program whenever a number that was not supposed to be a leap year was inputted it did not print the else statement.
Note: This was written in the IDE BlueJ so io was automatically imported hence why I did not import it
/**
* Reads a user inputted integer value and determines if it is a leap year
* Created by Oh boy I suck at this
* 9 September 2019
*/
import java.util.Scanner;
public class LeapYear
{
public static int getYear(String prompt)
{
String newLine = System.getProperty("line.separator");
int value = 0;
boolean flag = true;
while (flag)
{
Scanner scan = new Scanner(System.in);
System.out.println(prompt + ": ");
try
{
value = scan.nextInt();
flag = false;
}
catch(java.util.InputMismatchException e)
{
System.out.println("What you have inputed was not an int.");
System.out.println(newLine);
}
}
return value;
}
public static void main (String[] args)
{
int year = getYear("Input the year ");
final int leapYear = year/4;
if(year % 4 == 0){
if(year % 100 >= 1){
if(year % 400 >= 1){
System.out.println("The year inputted: " + year + " is equivilant to " + leapYear + " leap year(s).");
}
else{
System.out.println("The year inputted: " + year + " is not a leap year.");
}
}
}
}
}
Let us look at your if statements, and remember the rules for leap years.
Understanding leap years
In general, a leap year is a year that is divisible by four, i.e. where the statement year % 4 == 0 is true.
But: If a year is not a leap year, when it is divisible by 100. I.e. year % 100 == 0 is true.
Exception: When that is also divisible by 400, i.e. year % 400 == 0 is true - then we have a leap year.
Basically: divisible by four yields a candidate - you then have to study it further to make a final decision.
Decision tree
Is it a leap year candidate? year % 4 == 0 Otherwise: Display "not a leap year"
Is it a leap year exception (every 100 years)? year % 100 == 0 Otherwise: Display "not a leap year"
Is it a leap year exception exception (every 400 years)? year % 400 == 0 True => Display "leap year", False => Display "not a leap year"
Your implementation
Let's first look at your if statement.
Your first if statement checks whether the year is divisible by four. This is so that you know whether you deal with a leap year candidate. So this is correct - but you forgot to deal with the case, when the year is NOT a leap year (so here you miss a possible "is not a leap year" output)
Now it gets a bit confusing. You check whether the year is NOT divisible by 100. If a leap year candidate is NOT divisible by 100 it IS a leap year. So you can output success, but you have to deal with the "else" case.
The third if is nested in the wrong if block. It belongs into the else block of the parent.
Hints
Try to get an understanding on how the input and the output relate to each other and try to hit every if / else.
Whenever you write an if think about whether you need the corresponding else block.
If things get weird, try to "trace" your program with "breadcrumb outputs": System.out.println("1"); System.out.println("2"); ... on every line where you deal with branching or looping (if,else,switch,while...) this will trace every step the program does on the command line. You can use this until your school encourages you to use a proper IDE.
Don't forget: Practice makes perfect ;)
Pseude code (spoiler)
Only use this if you're completely stuck.
if (year % 4 == 0) {
// this might be a leap year - we need to dig further
if (year % 100 == 0) {
if (year % 400 == 0) {
print "leap year"
} else {
print "not a leap year"
}
} else {
print "leap year"
}
} else {
print "not a leap year"
}
Bottom line
Some of your logic is incorrect and you forget to implement the else branches.
HTH
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
import java.util.Scanner;
public class LeapYearTester{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a year");
int year_input = input.nextInt();
// now make a Year object
Year theYear = new Year(year_input);
// now check to see if it's a leap year
if (theYear.isLeapYear())
System.out.println("That's a leap year!");
else
System.out.println("That's not a leap year!");
}
}
public class Year
{
// declare your instance variables here
private int theYear;
private int Year;
// write your constructor here
public Year(int y)
{
y=Year;
}
static boolean isLeapYear(final int Year) {
return Year % 4 == 0 && (Year % 100 != 0 || Year % 400 == 0);
//(((Year%4==0) || (Year%400)) && ((!Year%100==0) || (Year%400=0)))
}
}
The above is the Main and cannot be changed. Having trouble with class.
Not much modification of your original attempt other than adding a check to see if the user entered a valid year in this case between 1000 and 2999 inclusive using regex (I will leave it as a task for you to modify this code for what you consider as a valid year):
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LeapYearTester {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Please enter a year: ");
String yearInput = "";
String pattern = "^[12][0-9]{3}$";
Pattern r = Pattern.compile(pattern);
//checking is valid year
while(input.hasNext()){
yearInput = input.nextLine();
Matcher m = r.matcher(yearInput);
if(m.find()) {
System.out.println("You entered the valid year: " + m.group(0));
break;
} else {
System.out.println("Error: Not a valid year");
System.out.print("Please enter a year between 1000 and 2999 inclusive: ");
}
}
Year theYear = new Year(Integer.valueOf(yearInput));
if(theYear.isLeapYear()) {
System.out.println("That's a leap year!");
} else {
System.out.println("That's not a leap year!");
}
}
public static class Year {
private int year;
private Year(int y) {
year = y;
}
private boolean isLeapYear() {
if (year % 4 != 0) {
return false;
} else if (year % 400 == 0) {
return true;
} else if (year % 100 == 0) {
return false;
} else {
return true;
}
}
}
}
Example usage: Testing a leap year
Please enter a year: 2016
You entered the valid year: 2016
That's a leap year!
Example usage: Invalid input and testing a non leap year
Please enter a year: 3000
Error: Not a valid year
Please enter a year between 1000 and 2999 inclusive: 2015
You entered the valid year: 2015
That's not a leap year!
Try it here!
basically I am in the middle of my program that involves asking a user to enter a day,month, and year, and based on that entry I am supposed to create a method that calculates the number of days in the year, but of course I need a method that defines how many days are in each month, and a method that determines whether or not it is a leap year or not. I have established my methods, user input, but now I am having method/return issue. Here is what I have so far:
import java.util.Scanner;
public class DayNumber{
public static void main(String[] args){
int year;
int month;
int day;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the date's year (0001 - 9999): ");
year = keyboard.nextInt();
System.out.print("Enter the date's month (1 - 12): ");
month = keyboard.nextInt();
System.out.print("Enter the date's day (1 - 31): ");
day = keyboard.nextInt();
}
public static int numberOfDays(int day, int month, int year){
int numberOfDays;
return numberOfDays;
}
public static int daysInMonth(int month, int year){
int daysInMonth;
if (month ==1 || month==3 || month==5 || month==7 || month==8 ||
month==10 || month==12){
month = 31;}
if (month ==4 || month ==6 || month==9|| month==11){
month = 30;}
else if (month ==2){
if (){
}
}
return daysInMonth;
}
public static boolean isLeapYear(int year){
if (((year%4 == 0) && (year%100 != 0)) || (year%400 ==0)){
return true;
}
else{
return false;
}
}
}
I would appreciate any advice or tips. I am really new to Java so go ahead and critique away! Thanks.
There are several different ways. Yours looks fine to me.
But my favorite is this tiny little line :
daysInMonth = (month === 2) ? (28 + isLeapYear) : 31 - (month - 1) % 7 % 2;
If you are asking yourself : Why % 7 % 2 ?
Well, you have noticed that starting from august, the pattern is reverted, that's what we are doing here. We say that between 0 - 6 it's normal then if it's 7 (7 % 7 = 0) we are going back from the beggining). Then the % 2 is to alternate between 0 - 1.
Hope I made myself clear
Although your question is not clear. I tried to understand and here is my understanding:
Input date
Display number of days in month
Display whether year is leap year or not
Here is what I will do
Class MyDateHomework {
public static boolean isLeapYear(int year) {
//put logic to find leapyear
}
public static int daysInMonth(int month, int year) {
if(month == 2) {
return isLeapYear(year) ? 28 : 29;
}
//put logic to find days in month
}
public static void main(String[] args) {
//take input and call method to do homework
}
}
I am writing a program for class that is a leap year checker. I have the loop working from what I understand however it goes into an infinite loop still? Zero wont terminate the program. I've tried using else if, if, while, what have I done wrong? This is my third go at rewriting this and am completely lost now -_-. Any help or tips would be appreciated.
import java.util.Scanner;
public class LeapYearChecker {
public static void main(String[] args){
System.out.println("Please enter a date to find out if the year is a leap year.");
Scanner userInput = new Scanner(System.in);
int year = userInput.nextInt();
while(year == 0)
{
System.out.println();
}
if (year < 1582){
System.out.println("Please enter a date after 1582. The date you entered was" + year + ".");
}if((year % 4 == 0) && (year % 100 !=0) || (year % 400 == 0)){
System.out.println("That is a leap year");
}else{
System.out.println(year +" is not a leap year.");
}
}
}
while (year == 0)
{
System.out.println();
}
There's your problem, if the year is 0, your program will infinitely output a new line.
Furthermore, your ifs for checking if it is a leap year isn't inside the loop body, so even if you enter a non-zero number, the code will only run once.
Try the following code, be sure to read the comments to understand what's going on:
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int year = -1; //Give your int a default value so the main loop will execute
while (year != 0) //-1 not equal to zero, so your code will start
{
System.out.print("Please enter a year: "); //Now we get the value of the year
year = in.nextInt(); //Put it into our variable
if (year < 1582) //And if it's less than 1582
{
if (year != 0)
System.out.println("Year must not be less than 1582!"); //Notify the user, unless they are exiting the program
continue; //restart the while loop, this is quite a useful statement!
}
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) //Check if it's a leap year
System.out.println("That is a leap year!\n");
else
System.out.println("That is not a leap year :(\n");
//End of the loop, so it goes back to the beginning, which asks the user again for the year
//So if you enter 0 next the program will close
}
}
The first loop is infinite. You forgot to read the user input inside.
Your loop will only run if a user enters 0. And once they do, your program will be stuck in an infinite loop since you haven't changed the value of year inside your while.
I'm assuming that you want to keep prompting the user to keep entering numbers until they enter 0? Then I would restructure your main method so that it surrounds the code where you retrieve and process input. Like so:
System.out.println("Please enter a date to find out if the year is a leap year.");
Scanner userInput = new Scanner(System.in);
int year;
do {
year = userInput.nextInt();
/**
* Print some message based input.
*/
} while (year != 0); // Loop until user enters 0
/*
*Find if a year is leap or not
*/
public class LeapYear{
private static int leapYear;
public void setLeapYear(int leapYear){
this.leapYear = leapYear;
}// end method
public static void main (String[] args) {
LeapYear leap = new LeapYear();
leap.setLeapYear(2010);
leap.setLeapYear(2008);
leap.setLeapYear(1900);
leap.setLeapYear(2000);
leap.setLeapYear(1565);
// Is it Divisible by 4?
if (leapYear % 4 == 0) {
// Is it Divisible by 4 but not 100?
if (leapYear % 100 != 0) {
System.out.println(leapYear + ": is a leap year.");
}
// Is it Divisible by 4 and 100 and 400?
else if (leapYear % 400 == 0) {
System.out.println(leapYear + ": is a leap year.");
}
// It is Divisible by 4 and 100 but not 400!
else {
System.out.println(leapYear + ": is not a leap year.");
}
}
// It is not divisible by 4.
else {
System.out.println(leapYear + ": is not a leap year.");
}
}
}
I am new to Java and I wrote this code so that it would call for all five years into the boolean and generate answers for all of them. However it only calls the last one. How would I do this right?
Problem 1
The four first calls to setLeapYear:
leap.setLeapYear(2010); // leap.leapYear = 2010;
leap.setLeapYear(2008); // leap.leapYear = 2008;
leap.setLeapYear(1900); // leap.leapYear = 1900;
leap.setLeapYear(2000); // leap.leapYear = 2000;
gets overridden by the last one:
leap.setLeapYear(1565); // leap.leapYear = 1565;
I would probably write a boolean method called something like isLeapYear(int year) and do
System.out.println(isLeapYear(2010));
System.out.println(isLeapYear(2008));
...
Problem 2
leapYear is static, so you don't need to / shouldn't do LeapYear leap = new LeapYear(); (alternatively, you should drop the static modifier).
You need use separate object for each year or at least call the Leap Year checking method as soon as you crated the object for that year.
What you have is a series of call to a function that assigns a value to an attribute of the same object. Therefore, only the last statement has the effect as previous values are overwritten.
On additional note, your code doesn't seem to be properly organized. Whey do you make the checkings in Main and it seems that leapYear isn't defined anywhere.
Perhaps, you may want to define a function that returns true/false depending on the value of the passed parameter or the value of the year stored in object.
The code may look something like this:
leap.setLeapYear(2010); // leap.leapYear = 2010;
System.out.println(leap.isLeapYear());
leap.setLeapYear(2008); // leap.leapYear = 2008;
System.out.println(leap.isLeapYear());
leap.setLeapYear(1900); // leap.leapYear = 1900;
System.out.println(leap.isLeapYear());
leap.setLeapYear(2000);
System.out.println(leap.isLeapYear());
leap.setLeapYear(1565);
System.out.println(leap.isLeapYear());
You have to define isLeapYear() by moving the checks in main to that function.
I would be inclined to write the tests in your if statements in order from 400 to 4:
String result;
if (year % 400 == 0) {
result = "is a leap year.";
} else if (year % 100 == 0) {
result = "is not a leap year.";
} else if (year % 4 == 0) {
result = "is a leap year.";
} else {
result = "is not a leap year.";
}
System.out.println(year + ": " + result);