asking user for another prompt after wrong input in java - java

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;
}

Related

What to revise to make it implement modularization using methods

I already have these 3 codes made but our prof said to revise it again using methods now. Can you help or can you show me what to revise in each code?
1.)
public class HeadsOrTails {
public static void main(String[] args) {
int Heads = 0;
int Tails = 0;
for(long simulation = 1; simulation <= 2000000; simulation += 1)
{
int FlipResult = FlipCoin();
if(FlipResult == 1)
{
Heads += 1;
}
else if(FlipResult == 0)
{
Tails += 1;
}
}
System.out.println("Numer of heads appeared: " + Heads);
System.out.println("Numer of tails appeared: " + Tails);
}
private static int FlipCoin()
{
return (int) (Math.random() + 0.5);
}
}
2.)
import java.util.Scanner;
public class DecToHex {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
int number = input.nextInt();
int rem;
String result = "";
char
hex[]= {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
while(number > 0)
{
rem = number % 16;
result = hex[rem]+result;
number = number/16;
}
System.out.println("Hexadecimal Number: "+result);
}
}
3.)
import java.util.Scanner;
public class DayOfTheWeek {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Year: (e.g., 2012): ");
int year = input.nextInt();
System.out.print("Enter Month: 1-12: ");
int month = input.nextInt();
System.out.print("Enter the Day of the month: 1-31:");
int day = input.nextInt();
String DayOfTheWeek = ZCAlgo(day, month, year);
System.out.println("Day of the week is "+DayOfTheWeek);
}
public static String ZCAlgo(int day, int month, int year)
{
if (month == 1)
{
month = 13;
year--;
}
if (month == 2)
{
month = 14;
year--;
}
int q = day;
int m = month;
int k = year % 100;
int j = year / 100;
int h = q + 13*(m + 1) / 5 + k + k / 4 + j / 4 + 5 * j;
h = h % 7;
switch (h)
{
case 0: return "Saturday";
case 1: return "Sunday";
case 2: return "Monday";
case 3: return "Tuesday";
case 4: return "Wednesday";
case 5: return "Thurday";
case 6: return "Friday";
}
return "";
}
}
3.)
import java.util.Scanner;
public class DayOfTheWeek {
/* *****************************************************************************
METHOD NAME : main
DESCRIPTION : Executes the main program to test the class
DayOfTheWeek
********************************************************************************/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Year: (e.g., 2012): ");
int year = input.nextInt();
System.out.print("Enter Month: 1-12: ");
int month = input.nextInt();
System.out.print("Enter the Day of the month: 1-31:");
int day = input.nextInt();
String DayOfTheWeek = ZCAlgo(day, month, year);
System.out.println("Day of the week is "+DayOfTheWeek);
}
public static String ZCAlgo(int day, int month, int year)
{
if (month == 1)
{
month = 13;
year--;
}
if (month == 2)
{
month = 14;
year--;
}
int q = day;
int m = month;
int k = year % 100;
int j = year / 100;
int h = q + 13*(m + 1) / 5 + k + k / 4 + j / 4 + 5 * j;
h = h % 7;
switch (h)
{
case 0: return "Saturday";
case 1: return "Sunday";
case 2: return "Monday";
case 3: return "Tuesday";
case 4: return "Wednesday";
case 5: return "Thurday";
case 6: return "Friday";
}
return "";
}
}
Your professor wants you to avoid typing duplicate code. They want you to minimize the amount of code you have to repeatedly type. For example, look at the main method from your DayOfTheWeek class.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Year: (e.g., 2012): ");
int year = input.nextInt();
System.out.print("Enter Month: 1-12: ");
int month = input.nextInt();
System.out.print("Enter the Day of the month: 1-31:");
int day = input.nextInt();
//After this is more code below that we don't care about for now
}
You had to do 3 System.out.print() calls. You also did 3 input.nextInt() calls. That's 6 calls total.
Notice how there is a System.out.print() call, and then a input.nextInt() call immediately after? We can slim that down to something like this.
public static int fetchInput(Scanner input, String message) {
System.out.print(message);
return input.nextInt();
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int year = fetchInput(input, "Enter Year: (e.g., 2012): ");
int month = fetchInput(input, "Enter Month: 1-12: ");
int day = fetchInput(input, "Enter the Day of the month: 1-31:");
//After this is more code below that we don't care about for now
}
Now, we only have to type fetchInput() 3 times, which has a call to both System.out.print() and input.nextInt(), giving us a total of 5 calls.
So, 5 is less than 6, which means we have made progress towards our goal, but since it is only one less call, it may not seem significant. But in reality, there's a lot more repeats in your code - I just handed you one of them. On top of that, your professor is teaching you good habits that will help you if you ever become a programmer. What if instead of fetching 3 things, you needed to fetch 20? This is common in the real world, by the way. Using your old style, you would have had to type 20 System.out.print() and 20 input.nextInt() calls at least, putting you at around 40 calls. But doing it this new way, you would only need to type 20 fetchInput() calls, which has a System.out.print() call and an input.nextInt() call within it, putting our total at 22 calls for the new method. 40 vs 22 things to type is an easier to see example of how writing code that minimizes retyping the same thing saves you time.

Why do I keep geting: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4

I'm new to java and I keep getting
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4"
I've read similar questions on here, and tried to apply the fixes but none of them seem to work. Maybe I'm applying them wrong?
The error I get points to the line of code indicated by <<<<<<<<<
But the method I'm editing that caused the error to appear is indicated by ******
The code used to compile and run just fine before I added the defaultHolidays method (the method I'm editing that is causing the error). The goal of this method is to take the contents of a file and display them on the calendar that is printed to screen via an array. The contents of the file look like this:
1/1 New_Year's_Day
01/18 M_L_K_Day
and so on
Here's my code, sorry it's so long:
// Import general tools
import java.io.*;
import java.io.File; // Import the File class
import java.util.*;
// Import tools to get current date
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
// Start of class
public class RCal3Winter21 {
// Start of main method
public static void main (String[] args) throws FileNotFoundException {
// define the basics
String[][] strEventArray = new String[12][]; // creates the array to be filled later
// helps run or break out of the program
int intRunCode = 1;
// helps prevent invalid input
int intRequestedMo = 15;
// greet the user
System.out.println();
System.out.printf("%30s %n", "Welcome to CalintEndar!");
System.out.printf("%36s %n", "~ for all your planning needs ~");
System.out.println();
// indicates how many boxes(days) are associated with each month
strEventArray = sizeOfArray (strEventArray);
//begin program in earnest
runMenu(intRequestedMo, strEventArray);
} // intEnd main method
// compiles on scratchpaper
// removes leading zero from month & converts to int
public static int noZoMo(String strTempDate) {
//break temp date string into individual chars
char month0 = strTempDate.charAt(0);
char month1 = strTempDate.charAt(1);
char slash = strTempDate.charAt(2);
char day1 = strTempDate.charAt(3);
char day2 = strTempDate.charAt(4); <<<<<< This is the line the error highlights
String strMo;
// If/else to display month w/out leading 0s
if (month0 == '0') {
strMo = String.valueOf(month1);
} else {
strMo = String.valueOf(month0) + String.valueOf(month1);
} // End of if/else loop to display month w/out leading 0s
// converts month from string to int
int intMo = Integer.parseInt(strMo);
// returns month without leading zeros
return intMo;
}
// compiles on scratchpaper
// removes leading zero from day & converts to int
public static int noZoDay(String strTempDate) {
//break temp date string into individual chars
char month0 = strTempDate.charAt(0);
char month1 = strTempDate.charAt(1);
char slash = strTempDate.charAt(2);
char day1 = strTempDate.charAt(3);
char day2 = strTempDate.charAt(4);
String strDay;
// If/else to display day w/out leading 0s
if (day1 == '0') {
strDay = String.valueOf(day2);
} else {
strDay = String.valueOf(day1) + String.valueOf(day2);
} // End of if/else loop to display day w/out leading 0s
// converts day from string to int
int intDay = Integer.parseInt(strDay);
// returns day without leading zeros
return intDay;
}
// compiles in scratchpaper
// displays the menu and gather's the user's response
// returns response as a string to be worked with
public static String menuDisplay() {
// prints menu and prompts for input
System.out.println();
System.out.println("Please pick from the menu below");
System.out.println("\t\"e\" to enter a date and display it's calendar.");
System.out.println("\t\"ev\" to input an event.");
System.out.println("\t\"fp\" to save your calendar to a file");
System.out.println("\t\"t\" to get today's date and display today's calendar");
System.out.println("\t\"n\" to display the next month");
System.out.println("\t\"p\" to display the previous month");
System.out.println("\t\"q\" to quit CalintEndar");
// Scanner to gather user input
Scanner in = new Scanner(System.in);
// assigns user input to string
String command = in.nextLine();
// ignores case used
command = command.toLowerCase();
// returns the user input
return command;
} // intEnd menueDisplay method
// can't run in scratchpaper, too many method calls
// converts the user input to actions
public static void runMenu(int intRequestedMo, String[][] strEventArray) throws FileNotFoundException {
// method tools
boolean booRunProg = true; // value continues to run or breaks out of while loop
String strUsrInput;
// while loop to run menu selection & allow exit
while (booRunProg == true) {
strUsrInput = menuDisplay(); // sets input val frm menuDisplay to local str
// for use in this method/while loop
switch (strUsrInput) { // checks user input against menu options
case "e": // user requests specific date
intRequestedMo = optionE(strEventArray);
break;
case "t": // user requests today's date
intRequestedMo = optionT(strEventArray);
break;
case "n": // user wants to see the next month
intRequestedMo = optionN(intRequestedMo, strEventArray);
break;
case "p": // user wants to see previous month
intRequestedMo = optionP(intRequestedMo, strEventArray);
break;
case "ev": // user wants to add event
strEventArray = optionEV(strEventArray);
break;
case "fp": // user wants to save event
optionFP( strEventArray);
break;
case "q": // user wants to quite program
System.out.println("Thanks for using Calendar!");
booRunProg = false;
break;
default: // user made an error, try again
System.out.println("Invalid command. Please try again.");
break;
} // end switch case
} // end while loop
} // end runMenu method
// runs in scratchpaper, but without method call
// user enters a requested date
public static int optionE(String[][] strEventArray){
// Prompt user
System.out.println("What date would you like to see? (mm/dd)");
// Scanner to gather user input
Scanner input = new Scanner(System.in);
// set user input to a string
String strTempDate = input.next();
// remove the leading zeros from the current date
int intRequestedMo = noZoMo(strTempDate);
// returns the value of the current date as a string
drawCalnDate(strEventArray, intRequestedMo);
return intRequestedMo;
} // end optionE method
// runs in scratchpaper without method call
// show today's date
public static int optionT(String[][] strEventArray)
throws FileNotFoundException {
// get current date
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd");
LocalDateTime now = LocalDateTime.now();
// convert current date information to a string
String strTempDate = dtf.format(now);
// remove the leading zeros from the current date
int intRequestedMo = noZoMo(strTempDate);
defaultHolidays(strEventArray, intRequestedMo);
drawCalnDate(strEventArray, intRequestedMo);
// returns the value of the current date as a string
return intRequestedMo;
} // end optionT method
// runs in scratchpaper w/out method calls
// user wants to see the next month
public static int optionN(int intRequestedMo, String[][] strEventArray)
throws FileNotFoundException {
// making sure there's a calendar on the screen
if (intRequestedMo == 15) {
System.out.println("Error. Must select a calendar first.");
return intRequestedMo;
} // end if
else { // ensure cal goes from december to january
if (intRequestedMo == 12){
intRequestedMo = 1;
defaultHolidays(strEventArray, intRequestedMo);
drawCalnDate(strEventArray, intRequestedMo);
} else {
intRequestedMo++;
defaultHolidays(strEventArray, intRequestedMo);
drawCalnDate(strEventArray, intRequestedMo);
return intRequestedMo;
} // end else
}// end first if
return intRequestedMo;
} // end optionN method
// runs in scratchpaper w/out method calls
// user wants to see previous month
public static int optionP(int intRequestedMo, String[][] strEventArray)
throws FileNotFoundException {
// making sure there's a calendar on the screen
if (intRequestedMo == 15) {
System.out.println("Error. Must select a calendar first.");
return intRequestedMo;
} else { // ensure cal goes from january to december
if (intRequestedMo == 1){
intRequestedMo = 12;
defaultHolidays(strEventArray, intRequestedMo);
drawCalnDate(strEventArray, intRequestedMo);
} else {
intRequestedMo--;
defaultHolidays(strEventArray, intRequestedMo);
drawCalnDate(strEventArray, intRequestedMo);
} // end second if/else
} // end first if/else
return intRequestedMo;
}
// user wants to add an event
public static String[][] optionEV (String[][] strEventArray) throws FileNotFoundException {
// create scanner
Scanner userIn = new Scanner(System.in);
// prompt for date for the event
System.out.println();
System.out.println("When is the event? (mm/dd format)");
// get date from user
String strNewEvDate = userIn.next();
// remove zeros and change to ints
int intMo = noZoMo(strNewEvDate);
int intDay = noZoDay(strNewEvDate);
// prompt for event name
System.out.println();
System.out.println("What's happening?");
System.out.println("Title the event in event_name format.");
System.out.println("19 characters or less");
// get event name from user
String strNewEvent = userIn.next();
// puts event in array
strEventArray[intMo-1][intDay-1] = strNewEvent;
// return updates to strEventArray
return strEventArray;
} // end optionEV method
// user wants to print a month to file
public static void optionFP(String[][] strEventArray) throws FileNotFoundException {
// create scanner
Scanner userIn = new Scanner(System.in);
// prompt user
System.out.print("What month would you like to print to a file?");
// get user input
int printMonth = userIn.nextInt();
//<<
} // end optionFP method
public static String[][] defaultHolidays (String[][] strEventArray, int intRequestedMo) *********
throws FileNotFoundException {
File readFile = new File("defaultHolidays.txt"); // checks for file to be read
String strFileDate = "temp";
String strFileEvent = "temp";
String event;
String date;
int intFileMo = 0;
int intFileDay = 0;
// new scanner to read the file
Scanner input = new Scanner(readFile);
//System.out.println();
// to print the file to the screen
while (input.hasNext()) {
date = input.next();
strFileEvent = input.nextLine().trim();
if (date.length() != 4) {
System.out.println("There is an error in the file");
System.out.println("Date must be in mm/dd format");
} else {
intFileMo = noZoMo(date);
intFileDay = noZoDay(date);
strEventArray[intFileMo-1][intFileDay-1] = strFileEvent;
}
} // end while
return strEventArray;
} // end method defaultHolidays
public static String[][] sizeOfArray (String[][] strEventArray) {
strEventArray[0] = new String[31];
strEventArray[1] = new String[28];
strEventArray[2] = new String[31];
strEventArray[3] = new String[30];
strEventArray[4] = new String[31];
strEventArray[5] = new String[30];
strEventArray[6] = new String[31];
strEventArray[7] = new String[31];
strEventArray[8] = new String[30];
strEventArray[9] = new String[31];
strEventArray[10] = new String[30];
strEventArray[11] = new String[31];
return strEventArray;
} // end method to indicate num boxes in each array "row"
// indicates how many days are in each month
public static int daysInMo(int intRequestedMo) {
// if then to determine number of days in month
if (intRequestedMo == 4 || intRequestedMo == 6 ||
intRequestedMo == 9 || intRequestedMo == 11) {
return 30;
}
else if (intRequestedMo == 2) {
return 28;
}
else {
return 31;
}
} // end daysInMonth method
// method to display month on top of calendar
public static void topDateDisp(int intRequestedMo) {
// declarations
String centSngl;
String centDbl;
String mon = "Monday";
String tue = "Tuesday";
String wed = "Wednesday";
String thu = "Thursday";
String fri = "Friday";
String sat = "Saturday";
String sun = "Sunday";
// if to account for double digits
if (intRequestedMo > 0 && intRequestedMo < 10) {
for (int i = 1; i <= 71; i++) { // for to center
System.out.print(" ");
} // end for to center month
System.out.println(intRequestedMo);
} // end if for single digit
else {
for (int i = 1; i <= 70; i++) { // for to center
System.out.print(" ");
} // end for to center month
System.out.println(intRequestedMo);
} // end else if double digit
// line break for aesthetics
System.out.println();
// print the days of the week at the top of the calendar
System.out.printf("%13s%21s%21s%19s%19s%21s%18s %n", mon, tue, wed, thu, fri, sat, sun );
} // end topDateDisp
// method to change start day of the week
public static int[] getStartEnd (int intRequestedMo) {
// declare array variable
int[] intStartEndAry = new int[2];
if (intRequestedMo == 2 || intRequestedMo == 3 || intRequestedMo == 11) {
intStartEndAry[0] = 1; // mon
intStartEndAry[1] = 7;
} else if (intRequestedMo == 6) {
intStartEndAry[0] = 0; // tues
intStartEndAry[1] = 6;
} else if (intRequestedMo == 9 || intRequestedMo == 12) {
intStartEndAry[0] = -1; // weds
intStartEndAry[1] = 5;
} else if (intRequestedMo == 4 || intRequestedMo == 7) {
intStartEndAry[0] = -2; // thurs
intStartEndAry[1] = 4;
} else if (intRequestedMo == 1 || intRequestedMo == 10) {
intStartEndAry[0] = -3; // fri
intStartEndAry[1] = 3;
} else if (intRequestedMo == 5) {
intStartEndAry[0] = -4; // sat
intStartEndAry[1] = 2;
} else {
intStartEndAry[0] = -5; // sun
intStartEndAry[1] = 1;
}
return intStartEndAry;
} // end getStartEnd
// Start of method to fill in date rows on the calendar
public static void drawDateRow (int intDaysInMo, int intRequestedMo, int intStart, int intEnd) {
String single = " ";
String dble = " ";
// for loop to create row length
for (int i = intStart; i <= intEnd; i++) {
if(i <= 9 && i > 0) {
System.out.print("|" + i + single);
} else if (i > 9 && i <= intDaysInMo) {
System.out.print("|" + i + dble);
} else { // handles the hanging days at the end of the month
System.out.print("|" + single + " ");
} // End of nested if/else loop to account for double digits
} // intEnd of for loop to draw calendar & dates
System.out.println("|"); // Draws last pipe to complete calendar
} // end method
public static void drawEventRow(int intRequestedMo, int intDaysInMo, String[][] strEventArray,
int intStart, int intEnd) {
// declarations
int intEvtLength;
String strEvtName;
int intNumSpaces;
// for to create row length, fill with events, or draw blanks
for (int i = intStart; i < intEnd; i++) { // creates row length
// if the requested day is more than 1 and less than the max days in the month
if ( i > 0 && i <= intDaysInMo) {
// if array slot has a value
if (strEventArray[intRequestedMo - 1][i - 1] != null){
// get the event name from the array
strEvtName = strEventArray[intRequestedMo - 1][i - 1];
// get the length of the event name
intEvtLength = strEvtName.length();
// make room for the event
intNumSpaces = 19 - intEvtLength;
// print the first | of the calendar design
System.out.print("|");
// print the event name
System.out.print(strEvtName);
// loop to print event or blank depending on array
for (int k = 1; k <= intNumSpaces; k++) {
System.out.print(" ");
} // end innnermost for loop
// if the array slot is null
} else {
System.out.print("| ");
} // end second if/else
// if the day number is less than 0 or more than max days of month
} else {
System.out.print("| ");
} // end first if/else
}// end for
} // end drawEventRow method
// Start of method to draw horizontal line for the calendar
public static void drawLine() {
// Start of for loop to draw horizontal line for the calendar
for (int i = 1; i <= 141; i++) {
System.out.print("~");
} // End of for loop to draw horizontal line for the calendar
System.out.println(); // line break
} // End of of method to draw horizontal line for the calendar
// Start of method to create spaces in the calendar
public static void drawSpace() {
// draws the blanks in the days
for (int j = 1; j <= 5; j++){
// Start of nested space for loop
for (int i = 1; i <= 7; i++) {
System.out.print("| ");
} // End of nested space for loop
System.out.println("|"); // Draws last pipe to complete calendar
} // End of method to create spaces in the calendar
}
// Start of method to draw calendar & dates together
public static void drawCalnDate(String[][] strEventArray, int intRequestedMo) {
// declare variables
int intDaysInMo;
int[] aryStartEnd = new int[2];
// initialize variables
intDaysInMo = daysInMo(intRequestedMo); // get num days in req'd month
aryStartEnd = getStartEnd(intRequestedMo); // get start/end values once
// separate the values of the array
int intStart = aryStartEnd[0];
int intEnd = aryStartEnd[1];
topDateDisp(intRequestedMo);
// if/else to display only required rows of weeks
if (intRequestedMo == 2) {
// Start of for loop to draw calendar & dates together
// each run through the for loop draws a row
for (int i = 1; i <= 4; i++) {
drawLine();
drawDateRow(intDaysInMo, intRequestedMo, intStart, intEnd);
drawEventRow(intRequestedMo, intDaysInMo, strEventArray, intStart, intEnd);
intStart += 7;
intEnd += 7;
drawSpace();
} // end for to draw cal
} else if (intRequestedMo == 5 || intRequestedMo == 8) {
// Start of for loop to draw calendar & dates together
// each run through the for loop draws a row
for (int i = 1; i <= 6; i++) {
drawLine();
drawDateRow(intDaysInMo, intRequestedMo, intStart, intEnd);
drawEventRow(intRequestedMo, intDaysInMo, strEventArray, intStart, intEnd);
intStart += 7;
intEnd += 7;
drawSpace();
} // end for to draw cal
} else {
// Start of for loop to draw calendar & dates together
// each run through the for loop draws a row
for (int i = 1; i <= 5; i++) {
drawLine();
drawDateRow(intDaysInMo, intRequestedMo, intStart, intEnd);
drawEventRow(intRequestedMo, intDaysInMo, strEventArray, intStart, intEnd);
intStart += 7;
intEnd += 7;
drawSpace();
} // end for to draw cal
} // end of if/else if/else
drawLine();
} // end drawCalnDate method
}// End of class
Your code explicitly assumes the date will have 5 characters in the form mm/dd, but your first input violates that assumption as it is only 1/1. If the date were formatted in all cases with 2-digit month and 2-digit date (i.e. 01/01), your code would work.
You need to use the date parsing capabilities that are built-in to Java (java.time package).

Why doesn't my date validation code work?

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.

JAVA Find day of the week from user entered date [duplicate]

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

How to incorporate error message in the program below?

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

Categories