my code doesn't return any value and i have no idea why. My assignment requires me to write a code that accepts date in mm/dd/yyyy format and im required to put leap year in. The problem is, i dont get back any input. Im an amateur ad i dont know what is wrong. Im also allowed to use Case statment but I'm not sure how to implement case.
import java.util.Scanner;
public class Question1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in).useDelimiter("/");
System.out.println("Please enter a date in mm/dd/yyyy format: ");
String mm = sc.next();
String dd = sc.next();
String yyyy = sc.next();
int month = Integer.parseInt(mm);
int day = Integer.parseInt(dd);
int year = Integer.parseInt(yyyy);
if (month <= 0 || month>12)
{
System.out.println("invalid month ");
}
if (year%4 != 0 || month == 02 || day >= 29)
{
System.out.println("invalid date");
}
if (month == 4 || month == 6 || month == 9 || month == 11 || day >= 31)
{
System.out.println("Invalid day");
}
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 || day >=32 )
{
System.out.println("Invalid day");
}
else
{
System.out.println("Valid date");
}
}
}
The code sets the delimiter to /. Then you enter something like 12/25/2016. The first sc.next() call gets the 12. The second one gets the 25. The third... waits, because it doesn't see another / so it doesn't know you're done. If you typed 12/25/2016/ with your current code, it would at least give output, even if that output isn't correct yet.
you want to use switch case then go through the below code:
import java.util.Scanner;
public class Question1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in).useDelimiter("/");
System.out.println("Please enter a date in mm/dd/yyyy/ format: ");
String mm = sc.next();
String dd = sc.next();
String yyyy = sc.next();
int month = Integer.parseInt(mm);
int day = Integer.parseInt(dd);
int year = Integer.parseInt(yyyy);
boolean valid = isValidDate(day,month,year);
if (valid == true)
{
System.out.println("Date is Valid");
}
else
{
System.out.println("Date is InValid");
}
}
public static boolean isValidDate(int day, int month ,int year)
{
boolean monthOk = (month >= 1) && (month <= 12);
boolean dayOk = (day >= 1) && (day <= daysInMonth(year, month));
return (monthOk && dayOk);
}
private static int daysInMonth(int year, int month) {
int daysInMonth;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10: // go through
case 12:
daysInMonth = 31;
break;
case 2:
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
daysInMonth = 29;
} else {
daysInMonth = 28;
}
break;
default:
// returns 30 even for nonexistant months
daysInMonth = 30;
}
return daysInMonth;
}
}
take input as 12/25/2016/, not this 12/25/2016.
Here is something to get you started:
final String DELIMITER = "/";
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a date in mm/dd/yyyy format:\n ");
String date = sc.next();
sc.close();
String[] dateParts = date.split(DELIMITER);
//check : if dateParts size is not 3 ....something is wrong
String mm = dateParts[0];
String dd = dateParts[1];
String yyyy = dateParts[2];
System.out.println(mm+" "+ dd +" "+ yyyy);
It seems you have put else in wrong place. Suppose you second condition is getting correct and all other false, then also your program will show it as valid date and same on the opposite side.
For example, say day is 30 for any date, then it will satisfy second condition and it will show you "Invalid date".
You should write if else as follows.
If{
If{
If{
}
}
}else{
}
All if must be in a nested if and then else. Your if else sequence is wrong.
Related
This question already has answers here:
java get day of week is not accurate
(3 answers)
Closed 6 years ago.
I have this code which is built to find day of the week when user enters date but currently it's not working as expected.
Also, I need to help with setting up loop to ask question again and again until user press "Control + Z" to exit.
Can anyone check and point me out issues. Also help with loop.
import java.util.Calendar;
import java.util.Scanner;
public class CalendarProject {
#SuppressWarnings({ "resource" })
public static void main(String[] args) {
Calendar c = Calendar.getInstance();
Scanner input = new Scanner (System.in);
//Enter the Day
System.out.println("Enter the day in number:");
int day1= input.nextInt( );
//Enter the Month
System.out.println("Enter the Month in number");
int month= input.nextInt( );
//Enter the Year
System.out.println("Enter the Year in number format");
int year= input.nextInt( );
//Display the day
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
System.out.println(String.format("%d/%d/%d",day1,month,year));
System.out.println(c.get(Calendar.DAY_OF_WEEK));
if (dayOfWeek == Calendar.SUNDAY) {
System.out.println("Sunday");
}
else if (dayOfWeek == Calendar.MONDAY) {
System.out.println("Monday");
}
else if (dayOfWeek == Calendar.TUESDAY) {
System.out.println("Tuesday");
}
else if (dayOfWeek == Calendar.WEDNESDAY) {
System.out.println("Wednesday");
}
else if (dayOfWeek == Calendar.THURSDAY) {
System.out.println("Thursday");
}
else if (dayOfWeek == Calendar.FRIDAY) {
System.out.println("Friday");
}
else if (dayOfWeek == Calendar.SATURDAY) {
System.out.println("Saturday");
}
}
}
1.You never set the input date in Calender object,hence it will never work as desired. So you need to use c.setTime(date); Here date is Date object.
2. For loop, you can use do while loop to ask user again and again.
Following is your modified code
public static void main(String[] args) {
Calendar c;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Scanner input = new Scanner (System.in);
try {
do{
System.out.println("Enter the day in number:");
int day1= input.nextInt();
//Enter the Month
System.out.println("Enter the Month in number");
int month= input.nextInt( );
//Enter the Year
System.out.println("Enter the Year in number format");
int year= input.nextInt( );
Date date = formatter.parse((String.format("%d/%d/%d",day1,month,year)));
System.out.println(date);
c= Calendar.getInstance();
c.setTime(date);
int day = c.get(Calendar.DAY_OF_WEEK);
if (day == Calendar.SUNDAY) {
System.out.println("Sunday");
}
else if (day == Calendar.MONDAY) {
System.out.println("Monday");
}
else if (day == Calendar.TUESDAY) {
System.out.println("Tuesday");
}
else if (day == Calendar.WEDNESDAY) {
System.out.println("Wednesday");
}
else if (day == Calendar.THURSDAY) {
System.out.println("Thursday");
}
else if (day == Calendar.FRIDAY) {
System.out.println("Friday");
}
else if (day == Calendar.SATURDAY) {
System.out.println("Saturday");
}
System.out.println("To exit press CTRL+Z(Windows) or CTRL+D(LINUX), or any key to continue");
input.nextLine();
}while (input.hasNextLine());
}catch(NoSuchElementException n){
System.out.println("NoSuchElementException");
}catch(ParseException pe){
System.out.println("invalid date");
}finally {
input.close();
System.out.println("exiting");
}
}
3. If you are using Java 8, you can get rid of all if else blocks by using java.time.DayOfWeek Enum. Just replace all your if else by following lines
DayOfWeek dayOfWeek = DayOfWeek.of((day+6)%7==0?7:(day+6)%7);
System.out.println(dayOfWeek);
I used ternary operator because DayOfWeek takes MONDAY as value of index 1 and Calender.DAY_OF_WEEk takes SUNDAY as value of index 1
I'm writing a program where I am supposed to have the user input a date from the year 0 - 4000. I'm supposed to see if the date is valid, and if it was a leap year or not. I'm having problems in my code.
I'm getting an else without error on line 57.
I also am not sure how to how to say if the date is valid or not.
IE: this date is valid, is a leap year - or is not valid is not a leap year ...etc...
I'm still a beginner so I dont want the code written for me but I would like to know how to fix it! Thank you.
import java.util.*;
public class LegalDate //file name
{
public static void main (String [] args)
{
Scanner kb = new Scanner (System.in); //new scanner
//name the variables
int month, day, year;
int daysinMonth;
boolean month1, year1, day1;
boolean validDate;
boolean leapYear;
//ask the user for input
//I asked the MM/DD/YYYY in seperate lines to help me visually with the program
System.out.println("Please enter the month, day, and year in interger form: " );
kb.nextInt();
//now I'm checking to see if the month and years are valid
if (month <1 || month >12)
{ month1 = true;}
if (year <0 || year >4000)
{year1= true;}
//I'm using a switch here instead of an if-else statement, which can also be used
switch (month) {
case 1:
case 3:
case 5: //months with 31 days
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6: //months with 30 days
case 9:
case 11:
numDays = 30;
break;
case 2:
if (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0)) //formula for leapyear
numDays = 29;
{
system.out.println("is a leap year");
}
else
numDays = 28;
{
system.out.println("is not a leap year");
}
break;
default:
System.out.println("Invalid month.");
break;
if (month1 == true)
if (day1 == true)
if (year1 == true)
System.out.println ("date is valid ");
else
if (month1 == false)
System.out.println ("date is invalid");
else
if (day1 == false)
System.out.println ("date is invalid");
else
if (year1 == false)
System.out.println ("date is invalid");
}}
}
On line 57, you open a new code block but nothing is able to access it. I believe you meant to type:
else{
numDays = 28;
system.out.println("is not a leap year");
}
As a small tip, you can change this:
if (month1 == true)
if (day1 == true)
if (year1 == true)
System.out.println ("date is valid ");
to this:
if (month1 && day1 && year1)
System.out.println ("date is valid ");
Since the boolean comparison operators return true or false, you can tell that the condition just needs to be boolean. Since month1, day1, and year1 are all boolean values, you dont need to compare them to anything.
What the condition means, in the event you don't know, is if month1 and day1 and year1 are all true, then print date is valid
Why don't you try Java 8 date time API
It validates date and do much more for you
Like
try {
LocalDate date =LocalDate.of(2016, 12, 31);
if(date.isLeapYear())
System.out.println("Leap year");
else
System.out.println("Not leap year");
}
catch(DateTimeException e) {
System.out.println(e.getMessage());
}
You don't appear to be placing the code between your 'if' and 'else' statements in curly brackets, which means that the statement will only apply to the next line. For example:
if (a)
b = true
c = true
else
d = true
is read as
if (a) {
b = true
}
c = true
else {
d = true
}
Hopefully, you can see how the compiler wouldn't understand this, as an 'else' statement must occur directly after its associated 'if' block.
I would suggest adding some methods to simplify your code. For example:
public static boolean isLeapYear(int year) {
return (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0));
}
Also, if you use boolean variables to store information, you can print it all neatly at the end. For example, you could instantiate a variable 'isValid' to true at the top of your code, set it to false if you calculate that the date is invalid, and use an if statement at the end to print your result.
I know you said you didn't want it written for you, but that's the easiest way to demonstrate the importance of methods. Hopefully you can see how this is more readable than your version?
import java.util.Scanner;
public class LegalDate {
static final int maxYear = 4000;
public static void main (String [] args) {
int month, day, year;
boolean leapYear, validDate = false;
Scanner kb = new Scanner (System.in);
System.out.println("Please enter the month, day, and year in interger form.");
System.out.print("Month: ");
month = kb.nextInt();
System.out.print("Day: ");
day = kb.nextInt();
System.out.print("Year: ");
year = kb.nextInt();
leapYear = isLeapYear(year);
validDate = isValidDate(month, day, year);
System.out.printf("%nThe date is %svalid and is %sa leap year.%n", validDate ? "" : "not ", leapYear ? "" : "not ");
kb.close();
}
public static int numDaysInMonth(int month, boolean isLeapYear) {
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
if (isLeapYear) {
return 29;
} else {
return 28;
}
default:
return 0;
}
}
public static boolean isLeapYear(int year) {
return (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0));
}
public static boolean isValidDate(int month, int day, int year) {
return (month >= 1 && month <= 12) && (day >= 1 && day <= numDaysInMonth(month, isLeapYear(year))) && (year >= 0 && year <= maxYear);
}
}
If you have any questions I'll try my best to answer them!
The syntax of if-else statement on line 50 of your program is not correct.
It's a dangling else. Enclosing the body of if and else statement within braces should resolve this.
if (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0))
{
numDays = 29;
system.out.println("is a leap year");
}
else
{
numDays = 28;
system.out.println("is not a leap year");
}
you can make use of IDE or give attention to compiler error message to resolve such errors.
I'm an beginner IT11 student and we're supposed to make a program that will read in the number of the day, the month, and the year a person was born.
For example, someone born on September 3, 1982, would enter the numbers
3, 9, and 1982
into three separate JOP.showInputDialogs.
If an incorrect value is entered, the program should give a very specific error message explaining why it is invalid and ask the user to enter the information again. A user should never have to reenter more than one of the values when an invalid entry is made (example, if the day is invalid, the user should only have to reenter the day, not the month or the year).
The program will then tell the person their birthdate with the following format:
You were born September 3, 1982.
The format of the date must be as shown above.
Important
- The program MUST do error checking for invalid months (valid between 1 and 12)
- The program MUST do error checking for invalid years (valid >= 1800)
- The program MUST do error checking for invalid day of month (valid between 1 and maxDay in month (30, 31, 28 or 29))
- The program MUST only allow Feb 29 on LEAP YEARS only.
The part I'm stuck on is incorporating an error message for invalid dates. For example, if I were to input April 31, the program should return an error message saying "April only has 30 days", etc. How do I do that? Here is what I've got so far.
import javax.swing.*;
public class A6DateProgram {
public static void main(String[] args) {
int year = getYearFromUser(); //gets user input for year
int month = getMonthFromUser(); //gets user input for month
int day = getDateFromUser(month, year); //gets user input for date
//tells the user their birthdate
System.out.println("You were born " + Months(month) + " " + day + ", "+ year + " " + ".");
} //main
//asks user for year
public static int getYearFromUser(){
String year; //asks user for year
int year1 = 0;
String errorMessage = "";
boolean isLeap = false;
do{
year = JOptionPane.showInputDialog(errorMessage + "Please enter the year you were born in. (>1800)");
if (year == null) {
System.out.println("You clicked cancel");
System.exit(0);
}
// parse string to an int
try {
year1 = Integer.parseInt(year); //parses recieved number to an int
} catch (Exception e) {
errorMessage = "Invalid integer\n"; //if user does not input valid integer
continue; //continues to condition [while(true);]
} // catch
isLeap = validateYear(year1);
if(year1 < 1800 || year1 > 2400){ //number limitation
errorMessage = "Your number must be greater than 1800 or less than 2400. \n"; //if user does not input a valid integer between limit
continue; //continues to condition [while(true);]
}
break;
} while(true);
return year1;
} //getYearFromUser
public static boolean validateYear(int year){
return (year % 400 == 0 ) ? true : (year%100 == 0)? false : (year % 4 == 0)? true: false;
}
//asks user for month
public static int getMonthFromUser(){
String month;
int num = 0;
String errorMessage = "";
do{
month = JOptionPane.showInputDialog(errorMessage + "Please enter the month you were born in as a valid integer. (ex. January = 1)");
if (month == null) {
System.out.println("You clicked cancel");
System.exit(0);
}
// parse string to an int
try {
num = Integer.parseInt(month);
} catch (Exception e) {
errorMessage = "Invalid integer\n";
continue; //continues to condition [while(true);]
} // catch
if(num > 12 || num < 1){
errorMessage = "A year only has 12 months. \n";
continue; //continues to condition [while(true);]
}
break;
} while(true);
return num;
} //getMonthFromUser
//asks user for date
public static int getDateFromUser(int month, int year){
String date;
int day = 0;
String errorMessage = "";
boolean ToF = false;
do{
date = JOptionPane.showInputDialog(errorMessage + "Please enter the date you were born in. (1-31)");
//user clicks cancel
if (date == null) {
System.out.println("You clicked cancel");
System.exit(0);
}
// parse string to an int
try {
day = Integer.parseInt(date);
} catch (Exception e) {
errorMessage = "Invalid integer\n";
continue; //continues to condition [while(true);]
} // catch
ToF = validate(year, month, day); //giving boolean ToF a method to validate the day
if(ToF == false){
errorMessage = "The month you input does not have that date. \n";
continue; //continues to condition [while(true);]
}
break;
} while(true); //do
return day;
} //getDateFromUser
public static boolean validate(int year, int month, int day){
switch(month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if(day < 1 || day > 31)
return false;
break;
case 2:
if(year%4 == 0 || (year%400 == 0 && year%100 != 0)){
if (day < 1 || day > 29)
return false;
}else{
if (day < 1 || day > 28)
return false;
}
break;
case 4:
case 6:
case 9:
case 11:
if(day < 1 || day > 30)
return false;
break;
}
return true;
} //validate
//resonse to user input for month
public static String Months(int month) {
switch (month) {
case 1: return "January";
case 2: return "Febrary";
case 3: return "March";
case 4: return "April";
case 5: return "May";
case 6: return "June";
case 7: return "July";
case 8: return "August";
case 9: return "September";
case 10: return "October";
case 11: return "November";
case 12: return "December";
default: return "Invalid";
} // switch
} //Months
} //A6DateProgram Class
Try with SimpleDateFormat()
String date = "3";
String month = "9";
String year = "1980";
SimpleDateFormat sdf1 = new SimpleDateFormat("ddMMyyyy");
SimpleDateFormat sdf2 = new SimpleDateFormat("MMMM dd, yyyy");
Date date1 = sdf1.parse((Integer.parseInt(date)<10?"0"+date:date)+(Integer.parseInt(month)<10?"0"+month:month)+year);
String ansStr = sdf2.format(date1);
System.out.println("You were born "+ansStr);
If you enter an invail date it automatically take the next date.
Eaxmple if the input is 29-02-2014 it will take as 01-03-2014
I'm having a hard time with a few things. I'm fairly new to Java and I can't figure out how to read the first two digits to determine 08 or 09 due to the Octal digits. Also I'm getting a return of null, 1, 199 which don't need to be there. Help would be appreciated.
import java.util.*;
public class Dates {
public static void main(String[] args) {
String January,February, March, April, May, June, July,
August, September,October, November, December, month;
January = February = March = April = May = June = July =
August = September = October = November = December = month = null;
Scanner myScanner = new Scanner(System.in);
System.out.print("Enter date in the format mm/dd/yyyy: ");
String input = myScanner.next();
String months = input.substring(0,1);
int monthInt = Integer.parseInt(months);
if (monthInt == 01){
month = January;
}
else if (monthInt == 02){
month = February;
}
else if (monthInt == 03){
month = March;
}
else if (monthInt == 04){
month = April;
}
else if (monthInt == 05){
month = May;
}
else if (monthInt == 06){
month = June;
}
else if (monthInt == 07){
month = July;
}
else if (monthDouble == 08){
month = August;
}
else if (monthDouble == 09){
month = September;
}
else if (monthInt == 10){
month = October;
}
else if (monthInt == 11){
month = November;
}
else if (monthInt == 12){
month = December;
}
else {
System.out.println("Invalid Month");
}
String days = input.substring(3,4);
int daysInt = Integer.parseInt(days);
if ((daysInt <= 31) && (monthInt == 1 || monthInt == 3 || monthInt ==
5 || monthInt == 7 || monthInt == 8 || monthInt == 10 || monthInt
== 12)){
daysInt = daysInt;
}
else if ((daysInt <= 30) && (monthInt == 4 || monthInt == 6 || monthInt
== 9 || monthInt == 11)){
daysInt = daysInt;
}
else if ((daysInt <= 28) && (monthInt == 2)){
daysInt = daysInt;
}
else
System.out.println("Invalid Day");
String year = input.substring(6,9);
int yearInt = Integer.parseInt(year);
if (yearInt >= 1900 && yearInt <= 2014) {
yearInt = yearInt;
}
else {
System.out.println("Year should be between 1900 and 2014");
}
String checkSlash = input.substring(2);
char slash = checkSlash.charAt(0);
if (slash == '/')
slash = slash;
else
System.out.println("Invalid format. Use mm/dd/yyyy");
System.out.println(month + " " + daysInt + ", " + year);
}
}
There are vastly better ways to do this, most notably using even Java's Date and SimpleDateFormat classes, but if you must know...
Don't include the leading zero on the integers. You're not going to be reading or otherwise dealing with octal values. January is the first month, and it's much more straightforward to represent it as 1.
I'll give you an alternative, if you really don't want to use SimpleDateFormat. Consider that we know the values all fall in an integral range (that is, they're all going to be less than 2.1 billion). If we let the Integer class do the work of parsing the value for us, then we can do this in much less code.
Further to that, we don't need to worry about weird substrings (which, by the way, yours will only grab the first element - which is problematic).
Let's use the String#split() method and break up the input string on forward slashes.
String[] brokenInput = input.split("/");
Now we're given by our format and convention that the month is in brokenInput[0], the day in brokenInput[1], and the year in brokenInput[2].
Parsing is easy then:
Integer monthInt = Integer.parseInt(brokenInput[0]);
Integer daysInt = Integer.parseInt(brokenInput[1]);
Integer yearInt = Integer.parseInt(brokenInput[2]);
try this for a simpler way
String strDate = "11/29/2009";
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date dateStr = formatter.parse(strDate);
Java will consider numbers with leading zeros as octals, and a digit in octal base cannot be larger than 7. You will get an error if you try to use 08, 09. You could use Strings instead:
if (months.equals("01"))
...
And I think (since you want to compare with "01", "02", ...) you should use substring(0,2):
String months = input.substring(0,2);
I'm going to assume that there is a reason why you are doing this the long way.
To start with, removing the leading 0 of your int values when checking the month, they convert the value to octal, which you don't need...
if (monthInt == 1) {
month = January;
} else if (monthInt == 2) {
month = February;
} else if (monthInt == 3) {
month = March;
} else if (monthInt == 4) {
month = April;
} else if (monthInt == 5) {
month = May;
} else if (monthInt == 6) {
month = June;
} else if (monthInt == 7) {
month = July;
} else if (monthInt == 8) {
month = August;
} else if (monthInt == 9) {
month = September;
} else if (monthInt == 10) {
month = October;
} else if (monthInt == 11) {
month = November;
} else if (monthInt == 12) {
month = December;
} else {
System.out.println("Invalid Month");
}
This...
String months = input.substring(0, 1);
Will get the first character of the input, but you've asked the user for mm/dd/yyyy, which suggests that you want a two digit value for the month and day...besides, what happens if they type in 12?
Instead you could use String[] parts = input.split("/"); to split the input String on the / delimiter, this (if the input is valid) will give you three elements, one each part of the date value.
Then you can use...
int monthInt = Integer.parseInt(parts[0]);
//...
int daysInt = Integer.parseInt(parts[1]);
//...
int yearInt = Integer.parseInt(parts[2]);
To convert the individual elements.
This raises the question that you should probably validate the input value in some meaningful way BEFORE you try and split it.
The month values are all null
String January, February, March, April, May, June, July,
August, September, October, November, December, month;
January = February = March = April = May = June = July
= August = September = October = November = December = month = null;
Which basically means you output will always start with null. You actually need to assign these some meaningful value.
I'll also parrot what every body else has said, unless you have a really good reason to do otherwise, I'd be using Calendar and some kind of DateFormat to do all this...
Updated with a (slightly over the top) example
This basically takes your idea and use SimpleDateFormat and Calendar to perform the actual checking of the input, for example...
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class Dates {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Date (mm/dd/yyyy):");
String input = kb.nextLine();
// This is a little excessive, but does a pre-check of the basic
// format of the date. It checks for a strict adhereance to
// the nn/nn/nnnn format. This might not be required as
// SimpleDateFormat can actually be configured to be lient in it's
// parsing of values
if (input.matches("[0-9]{2}/[0-9]{2}/[0-9]{4}")) {
try {
// Parse the String input to a Date object
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date date = sdf.parse(input);
// Create a Calendar, going to use this to compare the resulting
// Date value, as the parser will auto correct the input
Calendar cal = Calendar.getInstance();
cal.setTime(date);
// Split the basic input along the / delimeter
String parts[] = input.split("/");
boolean valid = true;
// Check each part to make sure it matches the components of the date
if (Integer.parseInt(parts[0]) != cal.get(Calendar.MONTH) + 1) {
valid = false;
System.out.println(parts[0] + " is not a valid month");
}
if (Integer.parseInt(parts[1]) != cal.get(Calendar.DATE)) {
valid = false;
System.out.println(parts[1] + " is not a valid day of the month");
}
if (Integer.parseInt(parts[2]) != cal.get(Calendar.YEAR)) {
valid = false;
System.out.println(parts[2] + " is not a valid year");
}
if (valid) {
// Print the result...
System.out.println(new SimpleDateFormat("MMMM dd, yyyy").format(date));
}
} catch (ParseException ex) {
System.out.println("Unable to parse " + input + "; invalid format");
}
} else {
System.out.println("Invalid format");
}
}
}
so i'm asking the user for a month and a year. month has to be one of the twelve months and year has to be a number and no letters. i'm trying to figure out the best way to make the program say "wrong input, try again" and prompt them for input again. here's the section of code i'm working with for the month section.
public class MonthLength {
public static void main(String[] args) {
int month = 0;
// Prompt the user to enter a month
SimpleIO.prompt("Enter a month name: ");
String userInput = SimpleIO.readLine();
if (userInput.trim().toLowerCase().equals("january")) {
month = 1;
} else if (userInput.trim().toLowerCase().equals("february")) {
month = 2;
} else if (userInput.trim().toLowerCase().equals("march")) {
month = 3;
} else if (userInput.trim().toLowerCase().equals("april")) {
month = 4;
} else if (userInput.trim().toLowerCase().equals("may")) {
month = 5;
} else if (userInput.trim().toLowerCase().equals("june")) {
month = 6;
} else if (userInput.trim().toLowerCase().equals("july")) {
month = 7;
} else if (userInput.trim().toLowerCase().equals("august")) {
month = 8;
} else if (userInput.trim().toLowerCase().equals("september")) {
month = 9;
} else if (userInput.trim().toLowerCase().equals("october")) {
month = 10;
} else if (userInput.trim().toLowerCase().equals("november")) {
month = 11;
} else if (userInput.trim().toLowerCase().equals("december")) {
month = 12;
}
// Terminate program if month is not a proper month name
if (month < 1 || month > 12) {
System.out.println("Illegal month name; try again");
return;
}
and here's what i'm working with for the year section:
// Prompt the user to enter a year
SimpleIO.prompt("Enter a year: ");
userInput = SimpleIO.readLine();
int year = Integer.parseInt(userInput);
//Here, trying to use hasNextInt to make sure input is an integer
//If it's not, need to give an error message and prompt input again
// public boolean hasNextInt()
//Prompt input again if year is negative
if (year < 0) {
System.out.println("Year cannot be negative; try again");
return;
}
// Determine the number of days in the month
int numberOfDays;
switch (month) {
case 2: // February
numberOfDays = 28;
if (year % 4 == 0) {
numberOfDays = 29;
if (year % 100 == 0 && year % 400 != 0)
numberOfDays = 28;
}
break;
case 4: // April
case 6: // June
case 9: // September
case 11: // November
numberOfDays = 30;
break;
default: numberOfDays = 31;
break;
}
// Display the number of days in the month
System.out.println("There are " + numberOfDays +
" days in this month");
}
}
after seeing the code i'm sure it will be more clear what i'm asking. if they enter a word that isn't a month, prompt them and ask for input again. same thing if they enter a year that isn't integers. thanks in advance!
Running it in a loop, will do:
String userInput;
int month;
do{
SimpleIO.prompt("Enter a month name: ");
userInput = SimpleIO.readLine();
try{
month = Integer.parseInt(userInput);
} catch(NumberFormatException e){
continue;
}
}while(month <= 0 || month > 12);
You should create a loop that keeps prompting the user until the month is correctly inserted. Something in the following lines:
boolean correct_month = false; // Control variable
while(!correct_month)
{
int month = 0;
// Prompt the user to enter a month
SimpleIO.prompt("Enter a month name: ");
String userInput = SimpleIO.readLine();
...
// If the month is indeed correct
// then correct_month = true;
}
Then you apply the same idea to the years.
Instead of having all of those conditions on the month, I think it is better to add all the month strings into an ArrayList:
ArrayList <String> all_months = new ArrayList <String> ();
and then you just have to use all_months.indexOf with the string insert by the user. If it returns -1 the string is not a valid month, otherwise, it will give you the position where the month is on the list. For example
month = all_months.indexOf(userInput);
if(month != -1){
correct_month = true;
}
Thus, the complete solution would be something like:
ArrayList <String> all_months = new ArrayList <String> ();
all_months.add("january");
... // and so one
int month = 0; // Control variable
while(month <= 0)
{
// Prompt the user to enter a month
SimpleIO.prompt("Enter a month name: ");
String userInput = SimpleIO.readLine();
month = all_months.indexOf(userInput.trim().toLowerCase()) + 1;
}