Seamus W Seamus W - 1 month ago 7
Java Question

How to print multiple values for a true if statement in Java?

package leapYear;

import java.util.Scanner;
import javax.swing.JOptionPane;

public class leapYear {

public static void main (String[] args){

String yearInput = JOptionPane.showInputDialog("Enter the year here: ");
Scanner inputScanner = new Scanner(yearInput);
int year = inputScanner.nextInt();
inputScanner.close();

boolean leapYear = false;
{

if (year % 400 == 0)
{
leapYear = true;
}

else if (year % 100 == 0)
{
leapYear = false;
}

else if (year % 4 == 0)
{
leapYear = true;
}

else
{
leapYear = false;
}

if (leapYear)
JOptionPane.showMessageDialog(null, year + " IS a leap year!");

else JOptionPane.showMessageDialog(null, year + " is NOT a leap year!");
}
}
}


Basically what I want to try to do, is to put in a year between say, 500-1000, and for the program to print every single leap year in that time period. I'm new to coding and have no idea how to go about this. Thanks.

Answer

You simple put your code into some kind of loop:

for (int year = 500; year <= 1000; year++) {
 and here comes the code you already wrote

Of course, you might want to "beautify" things; by asking the user to provide the "lower" and "upper" limits of that loop:

for (int year = lowerLimitFromUser; year <= upperLimitFromUser; year++) {

In other words: the next concept that you want to study is about using the for loop.

And of course: to get their easily, you start by creating a helper method like

boolean isLeapYear(int year)

that you can call from within your loop. (ideally you first change your code to use that new method; to test that the restructuring didn't break the logic).

Comments