Repeating code for leap year - java

I already know how to check for a leap year, like this:
import java.util.*;
public class LeapYear {
public static void main(String[] args) {
int year;
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter year: ");
year = scan.nextInt();
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.");
}
}
}
}
But now I want to repeat this code. I've seen repeating code snippets before, and I can use just about any successfully, but this one is giving me trouble.
import java.util.Scanner;
public class LeapUpgrade
{
public static void main(String[] args)
{
String another = "y";
int year;
Scanner scan = new Scanner(System.in);
while (another.equalsIgnoreCase("y"))
{
System.out.println("Enter year: ");
year = scan.nextInt();
if ((year % 4 == 0) && year % 100 != 0)
{
System.out.println(year + " is a leap year.");
System.out.print("test another (y/n)? ");
another = scan.nextLine();
}
else if ((year % 4 == 0) && (year % 100 == 0)
&& (year % 400 == 0))
{
System.out.println(year + " is a leap year.");
System.out.print("test another (y/n)? ");
another = scan.nextLine();
}
else
{
System.out.println(year + " is not a leap year.");
System.out.print("test another (y/n)? ");
another = scan.nextLine();
}
}
}
}
What am I doing wrong here?
Thanks in advance for your help and don't judge.

To avoid repetition, just encapsulate the lines of code in a method
public static boolean isLeapYear(int year){
return (year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0);
}
You can then call it like this
if(LeapYear.isLeapYear(year)){
System.out.println("Leap year");
}else{
System.out.println("Not a leap year");
}

EDIT: See Rohan's answer. It's better for the sake of modularity and cleanliness/readability of code.
When you want to do something multiple times you typically just need a loop. As a hint, your loop should enclose this part of your code:
year = scan.nextInt();
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.");
}
I'll leave the type of loop and conditions to you.

Related

Evaluate Multiple Years to Find a Leap Year Using a Boolean Utility Method

Good afternoon everyone,
I am having an issue calculating multiple leap years from a boolean utility method. I've been told to use a loop, but have a hard time figuring out how and where to put it.
import java.util.Scanner;
public class LeapYear {
private static boolean isLeapYear(int year) {
if (year % 400 == 0 && year % 100 == 0) {
return true;
}
if (year % 100 == 0) {
return false;
}
if (year % 4 == 0) {
return true;
}
else {
return false;
}
}
public static void main(String[] args) {
int quitter = 0;
int negative = 0;
int year = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a year or -1 to quit: ");
year = scan.nextInt();
while (year != -1 && year < 1582) {
System.out.print("The Gregorian calendar was not adopted until 1582, please enter a year after 1582: ");
year = scan.nextInt();
}
if(year == -1) {
negative += year;
quitter++;
}
System.out.println(isLeapYear(year));
}
}
Just use a do-while loop:
public static void main(String[] args) {
int year = 0;
Scanner scan = new Scanner(System.in);
do{
System.out.println("Enter a year or -1 to quit: ");
year = scan.nextInt();
while (year < 1582) {
System.out.print("The Gregorian calendar was not adopted until 1582, please enter a year after 1582: ");
year = scan.nextInt();
}
if(year != -1) {
System.out.println(isLeapYear(year));
}
}while(year!=-1);
}

I can't get my program to print out a Leap year

The last method I was trying to get it to print out my program can't seem to get it to do it. I don't know what to do. And I'm in an online class so there is no one I could really ask. My teacher takes three days to reply.
import java.util.Scanner;
public class LeapYear {
public static void main(String[] args) {
displayInstructions();
int year = getYear();
isLeap(year);
}
public static void displayInstructions() {
System.out.println("This program asks you to enter a year as a 4 digit number. The output will indicate whether the year you entered is a leap year.");
}
public static int getYear() {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a year: ");
int year = reader.nextInt();
return year;
}
public static boolean isLeap(boolean year) {
boolean isLeapYear = false;
if (year % 4 == 0 && year != 100) {
isLeap = true;
}
else {
isLeap false;
}
}
public static void displayResuls( boolean isLeap, boolean year) {
if (isLeap)
{
System.out.println("Year" +year+" is a Leap Year.");
}
else {
System.out.println("Year" +year+" is not a Leap Year");
}
}
}
You never call displayResuls(isLeap(year), year).
Edit: also your declaration of displayResults is wrong, it should be int year instead of boolean year.
Your isLeap function should be like:
public static boolean isLeap(int year) {
boolean isLeapYear = false;
if ((year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0))) {
isLeapYear = true;
} else {
isLeapYear = false;
}
return isLeapYear;
}
Main mistake I think in condition. It is more complicated than yours.
Correct one:
(year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0))
For example, 2000 - leap, but 2100 - not.
This is your code rewritten. Just like others said, you never called displayResuls and there was some minor typos. Keep coding ;)
import java.util.Scanner;
public class LeapYear {
public static void main(String[] args) {
displayInstructions();
int year = getYear();
boolean ans = isLeap(year);
displayResuls(ans, year);
}
public static void displayInstructions() {
System.out.println("This program asks you to enter a year as a 4 digit number. The output will indicate whether the year you entered is a leap year.");
}
public static int getYear() {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a year: ");
int year = reader.nextInt();
return year;
}
public static boolean isLeap(int year) {
boolean isLeapYear = false;
if (((year % 4) == 0) && (year != 100)) {
isLeapYear = true;
} else {
isLeapYear = false;
}
return isLeapYear;
}
public static void displayResuls(boolean isLeap, int year) {
if (isLeap) {
System.out.println("Year " + year + " is a Leap Year.");
} else {
System.out.println("Year " + year + " is not a Leap Year");
}
}
}
Made few changes to your program and it works fine
public static void main(String[] args) {
displayInstructions();
int year = getYear();
System.out.println("Entered Year is "+isLeap(year));
}
public static void displayInstructions() {
System.out.println("This program asks you to enter a year as a 4 digit number. "
+ "The output will indicate whether the year you entered is a leap year.");
}
public static int getYear() {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a year: ");
int year = reader.nextInt();
return year;
}
public static boolean isLeap(int year) {
boolean isLeapYear = false;
if (year%4 == 0 && year != 100) {
return isLeapYear = true;
}
else {
return isLeapYear = false;
}
}

Why is my code skipping the 1st date for finding the next day?

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))

Test an int variable with a boolean in Java

I am still learning Java and am stuck and getting errors. Can someone help with a solution of how the best way to do this would be.
import java.util.Scanner;
public class LeapYear2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int year;
year = scan.nextInt();
boolean boolVar1,boolVar2,boolVar3;
boolVar1 = (year / 4);
boolVar2 = (year / 100);
boolVar3 = (year / 400);
if (boolVar1 == true && boolVar2 == true && boolVar3 == true)
{
System.out.println("This is a leap year.");
}
else if (boolVar1 == true && boolVar2 == true && boolVar3 != true)
{
System.out.println("This is not a leap year.");
}
else if (boolVar1 == true)
{
System.out.println("This is a leap year.");
}
else
{
System.out.println("This is not a leap year.");
}
}
}
If you want to know whether an int value is evenly divisible by another, you can do this:
boolVar1 = year % 4 == 0;
boolVar2 = year % 100 == 0;
boolVar3 = year % 400 == 0;
In Java, integer and boolean values are not interchangeable (unlike languages like C where 0 is false and any non-zero value is considered true). You need to use a comparison operator like ==. The % operator is the remainder function, which (from the rest of your code) looks like what you want to be using.
P.S. In the future, when you are asking about how to deal with errors, it would be very helpful if you posted the error message(s) in your question.
P.P.S. You should get in the habit of giving your variables meaningful names. For example, I would replace boolVar1 with divisibleBy4, etc. This will save you lots of headaches when you start writing more complex code.
Also, as others have pointed out, with a boolean variable b, recommended Java style is to use
if (...b...)
instead of
if (...b == true...)
and
if (...!b...)
instead of
if (...b == false...)
You need an explicit comparison to make an expression boolean. You do not need an explicit comparison with true on booleans, so the code should be as follows:
boolean boolVar1,boolVar2,boolVar3;
boolVar1 = (year % 4) == 0;
boolVar2 = (year % 100) == 0;
boolVar3 = (year % 400) == 0;
if (boolVar1 && boolVar2 && boolVar3)
{
System.out.println("This is a leap year.");
}
else if (boolVar1 && boolVar2 && !boolVar3)
{
System.out.println("This is not a leap year.");
}
else if (boolVar1)
{
System.out.println("This is a leap year.");
}
else
{
System.out.println("This is not a leap year.");
}
Note that boolVar != true and boolVar == false is equivalent to !boolVar.
use the modulo method for this.
if(year % 4 == 0){
System.out.println("This is a leap year.");
}
and so on. From what I can see you do not need to declare 3 separate int types for this. Just reuse this in each conditional statement.
You do not need all those booleans. You can simply test:
if ((year % 4 == 0) && (year % 100 != 0)){
System.out.println(year + " is a leap year.");
}
else if (year % 400 == 0){
System.out.println(year + " is a leap year.");
}
else {
System.out.println(year + " is not a leap year.");
}
rather than calculating so many conditions just put the following code
if(year%4==0)
System.out.println("The given year is leap year");
else
System.out.println("The given year is not leap year");
There is no situation where you stuck up between int value and boolean.
Use this code
boolVar1 = (year % 4) == 0;
boolVar2 = (year % 100) ==0;
boolVar3 = (year % 400) == 0;
Note that the original version would have worked in C.

Best Before Puzzle [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Spotify puzzle problem
Been working on this puzzle because I am new to Java and would like to learn it. SO, I have been solving this puzzle for Spotify. But everytime I submit it. It says wrong answer. Im pretty sure its right though can anyone see what I am missing. This is the problem. http://www.spotify.com/us/jobs/tech/best-before/
Here is my solution
import java.io.*;
import java.util.Arrays;
public class best_before {
static boolean next;
static String month, day, year;
public static void main(String[] args) throws IOException{
//Setup to grab the input
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String input = "";
input = br.readLine();
//Spilt the input to grab each integer entered by user
String bits = input;
String[] tokens = bits.split("/");
int a_value1 = Integer.parseInt(tokens[0]);
int b_value1 = Integer.parseInt(tokens[1]);
int c_value1 = Integer.parseInt(tokens[2]);
//Sort the array in order from lowest to highest
int[] int_array = new int[] {a_value1, b_value1, c_value1};
Arrays.sort(int_array);
int a_value = int_array[0];
int b_value = int_array[1];
int c_value = int_array[2];
year = Integer.toString(a_value);
month = Integer.toString(b_value);
day = Integer.toString(c_value);
//Check the integers entered to put them in the right order
int check_days = Integer.parseInt(day);
int check_month = Integer.parseInt(month);
int check_year = Integer.parseInt(year);
//Check to make sure none of the values are a negative integer
if(check_days < 0){
System.out.println(input + " is illegal");
System.exit(0);
}
else if(check_month < 0){
System.out.println(input + " is illegal");
System.exit(0);
}
else if(check_year < 0){
System.out.println(input + " is illegal");
System.exit(0);
}
//Will only change the values around if the highest date in the array is bigger than 31
if(check_days > 31){
//Only reorganize if year if larger than month
if(check_month > check_year){
month = Integer.toString(check_year);
}
//Otherwise just keep month at its current value
else{
month = Integer.toString(check_month);
}
//Change date and year around since one is bigger than the other
year = Integer.toString(check_days);
day = Integer.toString(check_month);
}
else if(check_year == 0){
if(check_month < check_days){
month = Integer.toString(check_month);
}
else{
month = Integer.toString(check_days);
}
}
//Get the length so I can zero pad the numbers
int length_year = year.length();
int length_month = month.length();
int length_day = day.length();
//Doing my zero pad thing right here
if(length_year == 1){
year = "200" + year;
}
else if(length_year == 2){
year = "20" + year;
}
else if(length_year == 3){
year = "2" + year;
}
if(length_month == 1){
month = "0" + month;
}
if(length_day == 1){
day = "0" + day;
}
//A last check to make sure everything is Kosher
int last_check = Integer.parseInt(year);
int last_check_month = Integer.parseInt(month);
int last_check_day = Integer.parseInt(day);
//Checking to see if it is a leap year. Is the year Divisible by 4?
if (last_check % 4 == 0) {
// Is the year Divisible by 4 but not 100?
if (last_check % 100 != 0) {
next = true;
}
// Is the year Divisible by 4 and 100 and 400?
else if (last_check % 400 == 0) {
next = true;
}
// It is Divisible by 4 and 100 but not 400!
else {
next = false;
}
}
// It is not divisible by 4.
else {
next = false;
}
//Check to make sure the date is legal and valid :)
if(last_check > 2999 || last_check < 2000)
{
//Date must be between 2000 and 2999 inclusive
System.out.println(input + " is illegal");
}
else if(last_check_month > 12)
{
//Date month must be less than 12
System.out.println(input + " is illegal");
}
else if(last_check_day > 31)
{
//Date day must be less than 31
System.out.println(input + " is illegal");
}
else if(next == false && last_check_day > 28 && last_check_month == 2){
//if next is false and the day is greater than 28 and its not a leap year something is wrong
System.out.println(input + " is illegal");
}
else if(next == true && last_check_day > 29){
//if next is true and the day is greater than 29 and it is a leap year something is wrongs
System.out.println(input + " is illegal");
}
else if(last_check_month == 4 && last_check_day > 30){
System.out.println(input + " is illegal");
}
else if(last_check_month == 6 && last_check_day > 30){
System.out.println(input + " is illegal");
}
else if(last_check_month == 9 && last_check_day > 30){
System.out.println(input + " is illegal");
}
else if(last_check_month == 11 && last_check_day > 30){
System.out.println(input + " is illegal");
}
else if(last_check == 2000){
//Check to make sure there are no other days that are zero too because you cant have two zeros
if(last_check_day == 0 || last_check_month == 0){
System.out.println(input + " is illegal");
}
else{
System.out.print(year + "-" + month + "-" + day);
}
}
else{
System.out.print(year + "-" + month + "-" + day);
}
}
}
Your program fails for the input 31/9/73, where it returns 2073-09-31 instead of 31/9/73 is illegal. Since September only has 30 days, your program should check for September (and a couple of other months), and output the error.
In the updated version, your program still fails the input 1/2/31; it should give 2031-1-2.
By the way, the main intent behind these puzzles is not to solve them, but to solve them elegantly. Try reducing the number of variables, and avoiding duplicate lines etc.

Categories