jeudi 29 janvier 2015

Format multiple if-else statements into methods

I have a program that checks for user date input and displays the output of the next date. However, I am using multiple if-else statements for the program.


I would like to alter it so that it will use methods to do the calculation instead of the repeated codes.


Below is an example of my code, take March and April for an example, one with 30 days, one with 31 days:



public class calDate{

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean dateValid = false;
int day = 0;
int month = 0;
int year = 0;
int nextDay = 0
int nextYear = 0;
String nextMonth = "";

System.out.print("Day: ");
day = scan.nextInt();

System.out.print("Month: ");
month = scan.nextInt();

System.out.print("Year: ");
year = scan.nextInt();

while (month < 1 && month > 12) //check if month is within 1 to 12
{
dateValid = false;
}

if ((month == 3) && (day >= 1 && day <= 31))
{
dateValid = true;
nextDay = day + 1;
nextMonth = " March ";
nextYear = year;

if (day == 31) {
nextDay = 1;
nextMonth = " April ";
nextYear = year;
}
}

else if ((month == 4) && (day >= 1 && day <= 30))
{
dateValid = true;
nextDay = day + 1;
nextMonth = " April ";
nextYear = year;

if (day == 30)
{
nextDay = 1;
nextMonth = " May ";
nextYear = year;
}
}
if (dateValid)
{
System.out.println("Tomorrow's date is: " + nextDay + nextMonth + nextYear);
}

else
{
System.out.println("Invalid input");
}
}


There are many repeated values, such as dateValid, nextDay, nextMonth, nextYear. How may I format my code so that I can put the statements into separate methods? Thank you.


Aucun commentaire:

Enregistrer un commentaire