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.
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
This question already has answers here:
Java variable scope in if statement [duplicate]
(5 answers)
Closed 5 years ago.
I was attempting to code a program that gives you the season based on an inputed month and day, but ran into a problem halfway through. After I intialize the variable month in an if statement, to check if the value inputed is a valid month, I cannot use the variable month later in the code to find the season as it gives me the error "cannot find symbol." Any help would be much appreciated.
import java.util.Scanner;
public class Date
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Please enter the number of the month: ");
if (in.hasNextInt() && in.nextInt() > 0 && in.nextInt() <= 12)
{
int month = in.nextInt();
}
else
{
System.out.println("Error: Invlaid month value");
}
System.out.println("Please enter the day: ");
int day = in.nextInt();
String season;
if (0 < month && month <= 3)
{
season = "Winter";
}
else if (3 < month && month <= 6)
{
season = "Spring";
}
else if (6 < month && month <= 9)
{
season = "Summer";
}
else if (9 < month && month <= 12)
{
season = "Fall";
}
}
}
The problem you encounter is that you have declared the variable within the if statement, meaning it may only be accessed within the { }. This article goes over the basics of variable scope in Java. You will only be able to access a variable from a scope if the variable was defined in a scope that is a subset of the current scope.
To achieve what you want, you will need to declare the variable outside the if-statement so that it can be accessible. Note you will need to handle the case when month is invalid otherwise you will have the default value of 0.
int month = 0;
if (in.hasNextInt()) {
month = in.nextInt();
if (!(month > 0 && month <= 12)) {
month = 0;
System.out.println("ERROR");
}
} else {
// Handle graceful exit
}
...
if (0 < month && month <= 3) { ... }
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!
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