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
Related
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;
}
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
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 last year.
Improve this question
For some reason I get a syntax error that says, "Syntax error, insert "}" to complete ClassBody." I checked every method, every statement to make sure I have complete opening and closing brackets, so I don't know why this is happening. Can anybody tell me why I might be getting this issue?
Copying the code into another file doesn't fix the problem, nor does going to Project > Clean.
import java.util.Scanner;
public class jloneman_Numerology
{
private String[] report;
private int day, month, year, num;
public jloneman_Numerology()
{
introduction();
report = new String[9];
num = 0;
}
public void introduction()
{
System.out.println("Welcome to ACME Numerology Reports! We will " +
"determine your special\nnumerology report based on your " +
"birth date.\n");
}
public void getDate()
{
char slash1, slash2;
do
{
System.out.print("Please enter your birth date (mm / dd / yyyy): ");
Scanner in = new Scanner(System.in);
String date = in.nextLine();
month = in.nextInt();
day = in.nextInt();
year = in.nextInt();
slash1 = date.charAt(3);
slash2 = date.charAt(8);
} while (validDate(slash1, slash2) == false);
calcNum();
}
public boolean validDate(char slash1, char slash2)
{
boolean isValid = true;
// Check for valid month
if (month < 1 || month > 12)
{
isValid = false;
System.out.printf("Invalid month: %d\n", month);
}
// Check for valid day
if (day < 1 || day > 31)
{
isValid = false;
System.out.printf("Invalid day: %d\n", day);
}
// Check for months with 30 days, else 31 days = invalid
if ((month == 4 || month == 6 || month == 9 || month == 11) && (day < 1 || day > 30))
{
isValid = false;
System.out.printf("Invalid day: %d\n", day);
}
else if (day < 1 || day > 31)
{
isValid = false;
System.out.printf("Invalid day: %d\n", day);
}
// Check for valid year
if (year < 1880 || year > 2280)
{
isValid = false;
System.out.println("Please enter a valid year between 1880 and 2280.");
}
// Check for correct separating character
if (slash1 != '/' || slash2 != '/')
{
isValid = false;
System.out.println("Invalid separating character, please use forward slashes");
}
if (leapYear() == true)
{
if (month == 2 && day > 29)
{
isValid = false;
System.out.printf("Invalid day for 2/%d: %d", year, day);
}
}
return isValid;
}
public boolean leapYear()
{
boolean isLeap;
if (year % 4 == 0 && year % 400 != 0)
isLeap = false;
else
isLeap = true;
return isLeap;
}
public void calcNum()
{
// Separate each digit of the date and add to a single number
// Test number for debugging
num = 5;
}
public void printReport()
{
report[0] = ":1: ";
report[1] = ":2: ";
report[2] = ":3: ";
report[3] = ":4: ";
report[4] = ":5: ";
report[5] = ":6: ";
report[6] = ":7: ";
report[7] = ":8: ";
report[8] = ":9: ";
System.out.println(report[num]);
}
}
78,0-1 Bot
Try removing (or commenting out) one method and see if the problem persists. If it does, remove or comment out an additional method, and so on, until the error disappears. Then restore everything but the last method.
If the error doesn't reappear, the problem is probably in that last method.
If it does reappear, the problem is more subtle; perhaps a control character embedded in the code. Try copying and pasting the code into a text-only editor (so any control characters will be ignored, save it, and recompiling.
I too had this error.
There are NO errors in the code above (when I used the code above as as a sub class).
I corrected my error by cleaning up my IDE's workspace and making sure the caller was working properly.
Project settings
Run settings
Made sure that main was listed properly
public static void main(String[] args) { ... }
I have faced the similar problem, solved it by deleting the class file and then recreated the file again and pasted the same code. It worked.
Take out the System.out.println and put it into the main function instead of the introduction() inside of the main(String[] args).
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have written this code that prompts the user to enter their month of birth and year of birth. There is some error checking: their month must be an integer and also in range from 1-12. The same for year. As it stands, I have two while loops and I can't think of a way to combine them to still get the error message when something is wrong. I can think of it if it was just going to say "Bad input: reenter" but it needs to say what is wrong with the input. It starts with month and that month has to be good before it moves on to asking the year. If the year is wrong, it will then ask to reenter year -- not go all the way back to month.
If anyone has any ideas, I'd appreciate it. The class used to check if it is an integer is one I'm required to use.
while(!monthDone) {
System.out.print("Enter Month of Birth: ");
monthInput=scan.next();
if(!(Type.isInteger(monthInput))) {
System.out.println("You need to enter an integer for month");
monthDone=false;
} else {
MOB = Integer.valueOf(monthInput);
if (MOB<1 || MOB>12) {
System.out.println("Your month is out of range");
monthDone=false;
} else {
monthDone=true;
}
while(!yearDone) {
System.out.print("Enter Year of Birth: ");
yearInput=scan.next();
if(!(Type.isInteger(yearInput))) {
System.out.println("You need to enter an integer for year");
}
else {
YOB = Integer.valueOf(yearInput);
if (YOB<1912 || YOB>2012) {
System.out.println("Your year is out of range");
yearDone=false;
}
else
yearDone=true;
}
}
}
}
} // else closed
} // Outer while close
I am just posting the while loop. When both monthDone && yearDone == true, I then go on to print how old they are, etc.
This is how I might lay it out without so much nesting.
Scanner scanner = new Scanner(System.in);
int month, year;
for (; ; scanner.nextLine()) {
System.out.println("What is your month and year of birth as [1-12] [1900-2012]");
if (!scanner.hasNextInt()) {
System.out.println("Your month is not a number");
continue;
}
month = scanner.nextInt();
if (month < 1 || month > 12) {
System.out.println("Your month is out of range");
continue;
}
if (!scanner.hasNextInt()) {
System.out.println("Your year is not a number");
continue;
}
year = scanner.nextInt();
if (year < 1900 || year > 2012) {
System.out.println("Your year is out of range");
continue;
}
break;
}
You can simply this thus:
while (!monthDone) {
...
}
while (!yearDone) {
...
}
so you don't progress to the year input until your month input is properly completed. You'll see that you can easily extend this to day-of-month etc.
/*
*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);