ally guarisco ally guarisco - 1 month ago 10
Java Question

How can I have two outputs in java but only have one show up depending on the outcome?

So in my Java class I am writing in eclipse neon code to show how many days are in a month according to the year and month. I have the code all written but I need an error message to pop up if you put in a number other then 1-12 for a month and I dont know how to have one output pop up and not the other. Heres what i have for my code:

import java.util.Scanner;

public class Month
{
public static void main(String[] args)
{
// Create a Scanner object to obtain information from user
Scanner input = new Scanner (System.in);

int MonthNum; // To hold the month from user input
int Year; // To hold the year
int numDays;

System.out.print("Please enter a month, 1-12:");
MonthNum = input.nextInt();
System.out.print("Please enter year:");
Year = input.nextInt();

if (MonthNum == 2)
{
if( (Year % 4 == 0) && (Year % 400 == 0) && !(Year % 100 == 0) )
numDays= 29;
else
numDays= 28;
}
else if (MonthNum == 1 || MonthNum == 3 || MonthNum == 5 || MonthNum == 7 || MonthNum == 8 || MonthNum == 10 || MonthNum == 12)
numDays = 31;
else
numDays = 30;

String Monthnam = null;
if (MonthNum == 1)
Monthnam = "January";
else if (MonthNum == 2)
Monthnam = "Febuary";
else if (MonthNum == 3)
Monthnam = "March";
else if (MonthNum == 4)
Monthnam = "April";
else if (MonthNum == 5)
Monthnam = "May";
else if (MonthNum == 6)
Monthnam = "June";
else if (MonthNum == 7)
Monthnam = "July";
else if (MonthNum == 8)
Monthnam = "August";
else if (MonthNum == 9)
Monthnam = "September";
else if (MonthNum == 10)
Monthnam = "October";
else if (MonthNum == 11)
Monthnam = "November";
else if (MonthNum == 12)
Monthnam = "December";

System.out.print(Monthnam + " " + Year + " " + "has" + " " + numDays + " " + "days");
}
}

Answer

After line 13 you would have a big if/else block

if( MonthNum <1 || MonthNum > 12 ){
    System.out.println("Invalid Month: " + MonthNum)
} 
else {
   ... the rest of your code
}