Updating Date inside a while loop, Java - java

Im trying to compare the real world date with a user input date within a while loop. Although the initial execute is correct, the second time its executing the date stays the same. Ive tried asking for the date inside the while loop and now most recently from within a class method but still the date stays the same.
How can I retrieve an up to date date?
import java.util.Date;
import java.util.Scanner;
class Watch {
Date CurrentTimeAndDate = new Date();
int CurrentMinutes() {
int currentMinutes = CurrentTimeAndDate.getMinutes();
System.out.println(currentMinutes);
return currentMinutes;
}
}
public class App {
public static void main(String[] args) throws InterruptedException {
Scanner input = new Scanner(System.in);
String timer = null;
int i = 0;
int num = 0;
Date TimeAndDate = new Date();
int getDay = TimeAndDate.getDay();
int getMonth = TimeAndDate.getMonth() + 1;
int getYear = TimeAndDate.getYear() + 1900;
int getMinutes = TimeAndDate.getMinutes();
Watch watch1 = new Watch();
String[] Month = { "", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
String[] Day = { "", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
System.out.println("Current time and date is " + TimeAndDate);
System.out.println("Printing my way! " + Day[getDay] + " " + Month[getMonth] + " " + getYear + " " + getMinutes);
System.out.println(" Enter a short description of what you want reminding about ");
String rem = input.nextLine();
System.out.println(" Enter date of reminder 1-7");
while (i < 7) {
System.out.println(i + 1 + " = " + Day[i + 1]);
i++;
}
int day = input.nextInt();
System.out.println("Enter Month of reminder");
i = 0;
while (i < 12) {
System.out.println(i + 1 + " " + "=" + " " + Month[i + 1]);
i++;
}
int month = input.nextInt();
System.out.println("Enter year");
int year = input.nextInt();
System.out.println("Enter Minutes, for testing purposes");
int userInputMinutes = input.nextInt();
System.out.println("Date set to remind you about " + rem + " " + Day[day] + " " + Month[month] + " " + year);
if (year > getYear) {
System.out.println("Its time to remind you about ");
} else {
System.out.println("Waiting");
}
int Mins = 0;
while (userInputMinutes != Mins) {
Mins = watch1.CurrentMinutes();
System.out.println("Current Minutes = " + getMinutes);
System.out.println("Entered minutes =" + userInputMinutes);
Thread.sleep(10000);
}
System.out.println("Its time to remind you about " + rem);
}
public static void Date(String time) {
}
}

You are setting the new Date() only once. So you will be getting that same in while loop iterations. To get a new date for every iteration, you have to set the below code inside the while loop
TimeAndDate = new Date();
int getDay = TimeAndDate.getDay();
int getMonth = TimeAndDate.getMonth() + 1;
int getYear = TimeAndDate.getYear() + 1900;
int getMinutes = TimeAndDate.getMinutes();
Watch watch1 = new Watch();
* Note: Date is a deprecated class. Please refer #Ole V.V. answer for
the correct class to use.*

First, use java.time, the modern Java date and time API, for you date and time work. Always. The Date class that you used (misused, really, I’ll get back to that) is poorly designed and long outdated. Never use that.
Getting current minutes
To get the current minute of the hour:
int currentMinutes() {
return LocalTime.now(ZoneId.systemDefault()).getMinute();
}
To read day of week or month from the user
Also use java.time for days of the week and for months. Your code is reinventing wheels. You should prefer to use library classes and methods that are already there for you. For example:
System.out.println(" Enter day of week of reminder 1-7");
for (DayOfWeek dow : DayOfWeek.values()) {
System.out.println("" + dow.getValue() + " = " + dow
.getDisplayName(TextStyle.SHORT_STANDALONE, Locale.ENGLISH));
}
int day = input.nextInt();
DayOfWeek dow = DayOfWeek.of(day);
System.out.println("You have chosen " + dow);
Example interaction:
Enter day of week of reminder 1-7
1 = Mon
2 = Tue
3 = Wed
4 = Thu
5 = Fri
6 = Sat
7 = Sun
2
You have chosen TUESDAY
Most methods of the Date class are deprecated for a reason
As I said, Date is poorly designed and long outdated. More than that, most of the constructors and methods of the class were deprecated in Java 1.1 in February 1997 because they work unreliably across time zones. So even if you insisted on using Date (which I hope you don’t), you should still stay far away from the deprecated methods including all of the get methods except getTime (which converts to milliseconds since the epoch).
Link
Oracle tutorial: Date Time explaining how to use java.time.

Related

how to iterate the days in java [duplicate]

This question already has answers here:
How to iterate through range of Dates in Java?
(15 answers)
Closed 5 years ago.
I am having doubt that how can i iterate through the days in java (Android). Requirement is i am displaying whole week dates.
Note: "whichever date user selects from it should start".
ex: If date is 29-10-2017 then the output will be 29-10-2017, 30-10-2017, 31-10-2017, 1-11-2017, 2-11-2017, 3-11-2017, 4-11-2017.
This is whole week.
I was able to get this result when dates are inside that month, but when dates are exceeding the month or year, i am not able to resolve them.
Please help, how do i resolve this issue.
Below is the code-snippet which i am using for this:
Calendar startCal = Calendar.getInstance();
startCal.setTime(new Date(Long.MAX_VALUE));
startCal.setTimeInMillis(minDate.getDateInMillis());
Calendar endCal = Calendar.getInstance();
endCal.setTime(new Date(Long.MAX_VALUE));
endCal.setTimeInMillis(maxDate.getDateInMillis());
// Add all weekend days within range to disabled days
for (int i = 0; i < 7; i++) {
while (startCal.before(endCal) || startCal.equals(endCal) || (startCal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY)) {
if (startCal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY
|| startCal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY
|| startCal.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY
|| startCal.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY
|| startCal.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY
|| startCal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
int key = Utils.formatDisabledDayForKey(startCal.get(Calendar.YEAR),
startCal.get(Calendar.MONTH), startCal.get(Calendar.DAY_OF_MONTH));
disabledDays.put(key, new MonthAdapter.CalendarDay(startCal));
}
startCal.add(Calendar.DATE, 1);
}
}
int daysInMonth = startCal.getActualMaximum(Calendar.DAY_OF_MONTH); // 31
And to poulet them inside some textview i am using this below code-snippet:
String date = dayOfMonth + "-" + (monthOfYear + 1) + "-" + year;
arr1 = new String[7];
datepicker_dailog.setText(date);
// String input = datepicker_dailog.getText().toString();
Log.e(TAG, "Date value1 is:--- " + date);
GregorianCalendar cal=new GregorianCalendar();
if (cal.isLeapYear(year)) {
dayOfMonth++;
}
String ar[] = date.split("[-]");
int day = Integer.parseInt(ar[0]);
int month = Integer.parseInt(ar[1]);
int year1 = Integer.parseInt(ar[2]);
Log.e(TAG, "new value is "+ day + " " + month + " "+ year1);
for(int j = 0; j < 7 ; j++) {
date_exp(day, month, year1);
date = day + "-"+month+"-"+year1;
arr1[j] = date;
Log.e(TAG, "loop is :--- "+ arr1[j]);
Log.e(TAG, "value in loop is :--- "+ day + " " + month + " "+ year1);
day++;
}
Log.e(TAG, "updated value is "+ day + " " + month + " "+ year1);
I am refering this library to inplement calendar with date:
https://github.com/code-troopers/android-betterpickers
Here i am modifying and storing the date values in textviews, Please check once:
#Override
public void onDateSet(CalendarDatePickerDialogFragment dialog, int year, int monthOfYear, int dayOfMonth) {
String date = dayOfMonth + "-" + (monthOfYear + 1) + "-" + year;
arr1 = new String[7];
datepicker_dailog.setText(date);
// String input = datepicker_dailog.getText().toString();
Log.e(TAG, "Date value1 is:--- " + date);
GregorianCalendar cal=new GregorianCalendar();
if (cal.isLeapYear(year)) {
dayOfMonth++;
}
String ar[] = date.split("[-]");
int day = Integer.parseInt(ar[0]);
int month = Integer.parseInt(ar[1]);
int year1 = Integer.parseInt(ar[2]);
Log.e(TAG, "new value is "+ day + " " + month + " "+ year1);
for(int j = 0; j < 7 ; j++) {
date = day + "-"+month+"-"+year1;
arr1[j] = date;
Log.e(TAG, "loop is :--- "+ arr1[j]);
Log.e(TAG, "value in loop is :--- "+ day + " " + month + " "+ year1);
day++;
}
Log.e(TAG, "updated value is "+ day + " " + month + " "+ year1);
//------------------------------------------------------------------------------------------
listView=(ListView)findViewById(R.id.addtime_container);
dataModels= new ArrayList<>();
try {
for (int i = 0; i < 7; i++) {
dataModels.add(new Model_Addtime(arr1[i]));
adapter = new Adapter_addtime(dataModels, getApplicationContext());
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Model_Addtime dataModel = dataModels.get(position);
Snackbar.make(view, dataModel.getDate_text() + "\n", Snackbar.LENGTH_LONG).setAction("No action", null).show();
}
});
}
} catch (NumberFormatException num){
num.printStackTrace(); num.getCause(); num.getMessage();
}
}
You should use this code
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
cal.add(Calendar.DATE, 2);
cal.add(Calendar.DATE, 3);
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(df.format(cal.getTime());
It will handle the month change and year change automatically.
In java 8 you can use streams like in this example
List<LocalDate> daysRange = Stream.iterate(startDate, date -> date.plusDays(1)).limit(numOfDays).collect(toList());
Get instance of calendar, set it to today's date. Calendar has a function of adding 1 day to specified date and it takes care of adding month, year etc. Below is the code. Haven't tested the code though.
// Define the format in which you want dates
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
//Get calendar instance
Calendar calendar = Calendar.getInstance();
//Set today's date to calendar instance
calendar.setTime(new Date());
//Initialize a list to get dates
List<String> dates = new ArrayList<>();
//Get today's date in the format we defined above and add it to list
String date = format.format(calendar.getTime());
dates.add(date);
//run a for loop six times to get 1 day added each time
for (int i = 0; i <= 5; i++){
//this will take care of month and year when adding 1 day to current date
calendar.add(Calendar.DAY_OF_MONTH, 1);
dates.add(format.format(calendar.getTime()));
}
//Then to show the dates to your text-
String listString = TextUtils.join(", ", dates);
yourtextview.setText(listString);
You can use the add() method of Calendar class. It can be used to add or subtract specified number of days to a Calendar instance. The following is a running piece of code
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
public class DateExample {
public static void main(String[] args) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-YYYY");
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
String date;
for (int i = 0; i <= 7; i++){
date = dateFormat.format(cal.getTime());
System.out.println(date);
cal.add(Calendar.DAY_OF_MONTH, 1);
}
}
}
You can use iterateDay method. Example usage also below.
public class DateClass {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
calendar.set(2017, Calendar.OCTOBER, 29);
new DateClass().iterateDay(calendar.getTime(), 7);
}
public void iterateDay(Date date, int iterateCount){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
dislayDate(date);
for (int i = 1; i < iterateCount; i++) {
calendar.add(Calendar.DATE, 1);
dislayDate(calendar.getTime());
}
}
public void dislayDate(Date date){
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(dateFormat.format(date));
}
}

Java Code Logic Error

When I input "today" in the code below, if(date_holder.contains("/")) executes. How do I fix this?
Sorry for the sloppiness of my code. Any help is appreciated.
import java.util.*;
import java.io.*;
import java.text.*;
/**
* Write a description of class Driver here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class Driver
{
//extra credit
//do you want to enter a date or use todays date can use api to get it
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int day = 0;
int month = 0;
int year = 0;
char choice;
String date_holder;
StringTokenizer stok;
int count = 0; // use this variable to create all of the sub menus
//for example 0 is the first sub menu 1 s the next sub menu
while(count == 0)
{
System.out.println("Enter a date or type 'today' for todays date \nor enter 'quit' to quit: ");
date_holder = keyboard.next();
date_holder.trim();//trim any white space
System.out.println("!## " + date_holder);
if(date_holder.contains("/"))
{
stok = new StringTokenizer(date_holder,"/");
month = Integer.parseInt(stok.nextToken());
day = Integer.parseInt(stok.nextToken());
year = Integer.parseInt(stok.nextToken());
Date date = new Date(day, month, year);
count = 1;
while(count == 1)
{
do
{
//zz
System.out.println("Current Date: " + month + "/" + day + "/" + year +
"\nEnter 'a' if you want to add days to the date \n" +
"or enter a 's' if you want to subtract the date \n" +
"or enter a 'd' get the days between the current date and another date \n " +
"or enter a 'f' if you want to format the date.\n");
choice = keyboard.next().charAt(0);
}while(choice != 'a' && choice != 's' && choice != 'd' && choice != 'f');
String number; //to store the user's number input
String answer;
if(choice == 'a')//too add the date
{
System.out.println("Enter a number to add:");
number = keyboard.next();
date.add(Integer.parseInt(number));
answer = date.toString();
System.out.println("answer: " + answer);
count = 0;
}
else if(choice == 's')//too subtract the date
{
System.out.println("Enter a number of days to subtract:");
number = keyboard.next();
date.subtract(Integer.parseInt(number));
answer = date.toString();
System.out.println("answer: " + answer);
count = 0;
}
else if(choice == 'd')//too get the days between
{
int inMonth, inDay, inYear = 0;
System.out.println("Enter a date to use with " + month + "/" + day +
"/" + year + ":");
number = keyboard.next();
if(number.contains("/"))
{
stok = new StringTokenizer(number,"/");
inMonth = Integer.parseInt(stok.nextToken());
inDay = Integer.parseInt(stok.nextToken());
inYear = Integer.parseInt(stok.nextToken());
Date inDate = new Date(inDay, inMonth, inYear);
Date outDate = new Date(day, month, year);
if(year < inYear)
{
System.out.println("The days between " + date.toString() +
"and" + inDate.toString() + " is " + inDate.daysBetween(outDate) + " days.");
}
else
{
System.out.println("The days between " + date.toString() +
"and" + inDate.toString() + " is " + outDate.daysBetween(inDate) + "days.");
}
count = 0;
}
}
else if(choice == 'f')//too change the format and (extra credit)
{
do
{
//zz
System.out.println("Current Date: " + month + "/" + day + "/" + year +
"\nEnter 's' if you want the format day//month//year \n" +
"or enter a 'l' if you want the format day of month, year \n" +
"or enter a 'j' to get the Julian date \n" +
"or enter a 'h' if you want to get the horoscope Zodiac of the date.\n" +
"or enter a 'c' if you want to get the Chinese Zodiac of the date.\n"+
"or enter a 'e' if you want to get the Easter date of the year.\n");
choice = keyboard.next().charAt(0);
}while(choice != 's' && choice != 'l' && choice != 'j' && choice != 'h' && choice != 'c' && choice != 'e');
//I don't need any if statments to verify the choices because
//it is all handled in the getDate() method
System.out.println(date.getDate(choice));
count = 0;//end the submenu loop
}
}
}
else if(date_holder.equals("today"))
{
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal));
}
else if(date_holder.equals("quit"))
{
count = -1;
}
}
System.out.println("goodbye!");
}
}
Your Code works fine when I give today it prints the today's date with the format you mentioned but change your code to below.
else if(date_holder.equals("today"))
{
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
}
You cannot format the calendar object you have to use getTime method to get the Date object.
Your code looks quite clumsy please study more about the Date api here

Compare two strings that contain a date to check if one is before or after the other

I've written some code for a client-server application which allows the server to set up 2 deadlines for 2 different items. These items have a deadline at which the server should display when the time reaches it.
Here is what I have so far:
String[] deadlines = new String[2];
Calendar deadline = Calendar.getInstance();
for(int i = 0; i < 2; i++)
{
System.out.print("Enter finishing time for item " + (i+1) + " in 24-hr format "); // Item 1
System.out.print("(e.g. 17:52) : ");
String timeString = input.nextLine(); // get input
String hourString = timeString.substring(0,2);
int hour = Integer.parseInt(hourString);
String minString = timeString.substring(3,5);
int minute = Integer.parseInt(minString);
deadline.set(year,month,date,hour,minute,0);
deadlines[i] = getDateTime(deadline);
System.out.print("\nDeadline set for item " + (i+1) + "\n");
System.out.println(getDateTime(deadline)+ "\n\n");
}
System.out.println("\nServer running...\n");
Calendar now = Calendar.getInstance();
System.out.print(deadlines[0]); // HERE
System.out.print(deadlines[1]); // AND HERE
// getDateTime(now) outputs the same as deadlines[0] + deadlines[1].
while(now.before(deadlines[0]) || now.before(deadlines[1])) // THIS LINE
{
//System.out.println(getDateTime(now));
try
{
Thread.sleep(2000);
}
catch (InterruptedException intEx)
{
}
now = Calendar.getInstance();
if (now.after(deadlines[0]))
System.out.println("\n\nDeadline reached" + deadlines[0] + "\n");
if (now.after(deadlines[1]))
System.out.println("\n\nDeadline reached" + deadlines[1] + "\n");
}
public static String getDateTime(Calendar dateTime)
{
//Extract hours and minutes, each with 2 digits
//(i.e., with leading zeroes if needed)...
String hour2Digits = String.format("%02d", dateTime.get(Calendar.HOUR_OF_DAY));
String min2Digits = String.format("%02d", dateTime.get(Calendar.MINUTE));
return(dateTime.get(Calendar.DATE)
+ "/" + (dateTime.get(Calendar.MONTH)+1)
+ "/" + dateTime.get(Calendar.YEAR)
+ " "+ hour2Digits + ":" + min2Digits);
}
I need to check whether now is before the values of deadlines[0] and deadlines[1]. How can I do this? There must be a better way than converting it into a string etc?
You may use LocalTime#parse, it takes the exact format you're wanting the user to enter.
String input = "17:52";
LocalTime lt = LocalTime.parse(input); // 17:52
Then pass it to a LocalDateTime#of with a LocalDate
LocalDateTime ldt = LocalDateTime.of(LocalDate.of(year, month, day), lt);
If you need to compare them, use compare(), isAfter() or isBefore()
while (LocalDateTime.now().isAfter(ldt)){
// doStuff
}
EDIT
If you want to access the object outside of the loop, keep going with the same array logic if you want.
LocalDateTime[] dateTimes = new LocalDateTime[2];
for (//){
datesTimes[i] // for example
}
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime dateTime = f.parseDateTime("2012-01-10 23:13:26");
DateTime now = new Date();
if(now.compareTo(dateTime)<=0){
// dateTime is in the past
}

Java Show Strike Line on Methods

Why does it show strike line on getDate(), getMonth() and getYear(). These methods are used to get current date, month and year but I don't know why it shows strike on these methods.
Code:
public class hello {
public static void main(String[] args) {
int days;
int month;
int year;
days = 24;
month = 10;
year = 1994;
System.out.println("Date of Birth: " + days + "/" + month + "/" + year);
Date d = new Date();
int t = d.getDate();
int x = d.getMonth() + 1;
int f = d.getYear() + 1900;
System.out.println("Current Date: " + t + "/" + x + "/" + f);
}
}
IDEs like Eclipse would strike the methods if they are deprecated, meaning they're not recommended for use because there is a better alternative. See the Javadocs of getDate():
Deprecated. As of JDK version 1.1, replaced by Calendar.get(Calendar.DAY_OF_MONTH).
Using Calendar methods:
Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH) + 1;
int year = calendar.get(Calendar.YEAR);
That's becuase they're deprecated. If you set the #deprecated in the info above a function, it'll strike methods over in most IDE's.
These specific functions are deprecated because the newer Calendar is a better option.
Try this.
int days;
int month;
int year;
days=24;
month=10;
year=1994;
System.out.println("Date of Birth: "+days+ "/" +month+ "/" +year);
LocalDate dd = LocalDate.of(year, month, days);
System.out.println("Current Date: " + dd);
System.out.println("Month: " + dd.getMonth());
System.out.println("Day: " + dd.getDayOfMonth());
System.out.println("Year: " + dd.getYear());
//If you would add year
LocalDate newYear = dd.plusYears(10);
System.out.println("New Date: " + newYear);
This is output:
Date of Birth: 24/10/1994
Current Date: 1994-10-24
Month: OCTOBER
Day: 24
Year: 1994
New Date: 2004-10-24

Setting Gregorian Calendar But Not Getting Correct Day of Week

In part of my program, I am manipulating the Gregorian Calendar by setting the date to what the user specifies. I am able to print the correct month, day, and year, but it is not showing the correct day of the week. Could someone please point out what is going on?
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Map.Entry;
public class MyCalendar {
GregorianCalendar calendar;
private HashMap<GregorianCalendar, Event> myCalHash;
GregorianCalendar dayCounter = new GregorianCalendar(); // capture today
Scanner sc = new Scanner(System.in);
static MONTHS[] arrayOfMonths = MONTHS.values();
static DAYS[] arrayOfDays = DAYS.values();
MyCalendar(){
calendar = new GregorianCalendar();
myCalHash = new HashMap<GregorianCalendar, Event>();
}
public HashMap<GregorianCalendar, Event> getMyCalHash(){
return myCalHash;
}
public void setMyCalHash(HashMap<GregorianCalendar, Event> myCalHash) {
this.myCalHash = myCalHash;
}
public void viewCalendar() {
System.out.print("[D]ay view or [M]view? ");
char userChoice = sc.next().charAt(0);
if(Character.toUpperCase(userChoice) == 'D'){ dayView(); }
else if(Character.toUpperCase(userChoice) == 'M'){ monthView(); }
else{
System.out.println("Invalid choice.");
}
}
public void dayView(){
//print day calendar
//GregorianCalendar dayCounter = new GregorianCalendar(); // capture today
System.out.println(arrayOfDays[calendar.get(Calendar.DAY_OF_WEEK) - 1] + ", " + arrayOfMonths[calendar.get(Calendar.MONTH)]
+ " " + calendar.get(Calendar.DATE) + ", " + calendar.get(Calendar.YEAR));
System.out.print("[P]revious or [N]ext or [M]ain menu ? ");
char userChoice = sc.next().charAt(0);
if(Character.toUpperCase(userChoice) == 'P'){
calendar.add(Calendar.DAY_OF_MONTH, -1);
dayView();
}
else if(Character.toUpperCase(userChoice) == 'N'){
calendar.add(Calendar.DAY_OF_MONTH, 1);
dayView();
}
else if(Character.toUpperCase(userChoice) == 'M'){
return;
}
else{
System.out.println("Invalid choice.");
return;
}
}
public void monthView(){
//print month calendar
int formatCounter = 0;
dayCounter.set(Calendar.DAY_OF_MONTH, 1);
System.out.println(" " + arrayOfMonths[calendar.get(Calendar.MONTH) ] + " " + calendar.get(Calendar.YEAR)); //prints the month and year
for(int i = 0; i < arrayOfDays.length; i++){
if(i == 0){
System.out.print(arrayOfDays[i]);
}
else{
System.out.print(" " + arrayOfDays[i]);
}
}//print days of week
System.out.println();
for(int i = 0; i < arrayOfDays.length; i++){
if(!arrayOfDays[i].equals(arrayOfDays[dayCounter.get(Calendar.DAY_OF_WEEK) - 1])){
System.out.print(" ");
formatCounter++;
}
else{
System.out.print(" " + calendar.getActualMinimum(Calendar.DAY_OF_MONTH) + " ");
formatCounter++;
break;
}
}
for(int i = 1; i < dayCounter.getActualMaximum(Calendar.DAY_OF_MONTH); i++){
if(formatCounter == 7){
System.out.println();
formatCounter = 0; //reset counter
}
dayCounter.roll(Calendar.DAY_OF_MONTH, true);
if(dayCounter.get(Calendar.DATE) <= 9){
System.out.print(" " + dayCounter.get(Calendar.DATE) + " ");
formatCounter++;
}
else{
System.out.print(dayCounter.get(Calendar.DATE) + " ");
formatCounter++;
}
}
System.out.print("\n[P]revious or [N]ext or [M]ain menu ? ");
char userChoice = sc.next().charAt(0);
if(Character.toUpperCase(userChoice) == 'P'){
calendar.add(Calendar.MONTH, -1);
dayCounter.add(Calendar.MONTH, -1);
monthView();
}
else if(Character.toUpperCase(userChoice) == 'N'){
calendar.add(Calendar.MONTH, 1);
dayCounter.add(Calendar.MONTH, 1);
monthView();
}
else if(Character.toUpperCase(userChoice) == 'M'){
return;
}
else{
System.out.println("Invalid choice.");
return;
}
}
public void goTo(){
System.out.print("Enter a date in MM/DD/YYYY format: ");
String userDate = sc.nextLine();
String[] dateArr = userDate.split("/");
calendar.set(GregorianCalendar.YEAR, Integer.parseInt(dateArr[2]));
calendar.set(GregorianCalendar.MONTH, Integer.parseInt(dateArr[0]));
calendar.set(GregorianCalendar.DATE, Integer.parseInt(dateArr[1]));
System.out.println(arrayOfDays[calendar.get(Calendar.DAY_OF_WEEK) - 1] + ", " +
arrayOfMonths[calendar.get(Calendar.MONTH) - 1] + " " + calendar.get(Calendar.DATE) + ", " + calendar.get(Calendar.YEAR));
//more stuff
}
}
Edit:
DAYS is an enum defined in a testerClass as follows:
enum DAYS
{
Su, Mo, Tu, We, Th, Fr, Sa;
}
Sample output:
If user enters today's date (03/12/2015)
Program should print:
Th, March 12, 2015
But program is printing:
Su, March 12, 2015
Another edit
Here is how my months are defined in an enum:
enum MONTHS
{
January, February, March, April, May, June, July, August, September, October, November, December;
}
John Bollinger's answer points out the reason why you're seeing this anomaly, due to the fact that the months are 0-based, not 1-based, and your goTo method is setting the date incorrectly.
There's a couple issues here, that are giving you the false impression that you've set something up correctly everywhere except the day of week.
First:
calendar.set(GregorianCalendar.MONTH, Integer.parseInt(dateArr[0]));
You parse the user input and set the month of the calendar based on the user value (aka 03 for "March").
However, as John has pointed out, the month numbers are 0-based, so the calendar thinks 3 is "April".
This is all well and good for your lookup, as you're properly getting the day of week (Sunday), but for the wrong month (April), on day 12 in 2015.
Your lookup from the array though is properly giving you the impression that the Month is set right because you're using the Calendar's value for the month (which is 0 based).
You are incorrectly subtracting 1 from this value to look up the Month name, which makes you think that the day of week is wrong.
You need to fix two places (lookup and set):
calendar.set(GregorianCalendar.YEAR, Integer.parseInt(dateArr[2]));
calendar.set(GregorianCalendar.MONTH, Integer.parseInt(dateArr[0])-1);
calendar.set(GregorianCalendar.DATE, Integer.parseInt(dateArr[1]));
System.out.println(arrayOfDays[calendar.get(Calendar.DAY_OF_WEEK) - 1] + ", " +
arrayOfMonths[calendar.get(Calendar.MONTH)] + " " + calendar.get(Calendar.DATE) + ", " + calendar.get(Calendar.YEAR));
Calendar month numbers are zero-based, so for instance, Calendar.MARCH == 2. Your goTo() method does not account for that, and as a result, it sets the calendar to the wrong month.
Update:
It looks like you want this:
public void goTo(){
System.out.print("Enter a date in MM/DD/YYYY format: ");
String userDate = sc.nextLine();
String[] dateArr = userDate.split("/");
calendar.set(GregorianCalendar.YEAR, Integer.parseInt(dateArr[2]));
calendar.set(GregorianCalendar.MONTH, Integer.parseInt(dateArr[0]) - 1);
calendar.set(GregorianCalendar.DATE, Integer.parseInt(dateArr[1]));
System.out.println(arrayOfDays[calendar.get(Calendar.DAY_OF_WEEK) - 1] + ", "
+ arrayOfMonths[calendar.get(Calendar.MONTH)] + " "
+ calendar.get(Calendar.DATE) + ", "
+ calendar.get(Calendar.YEAR));
// ...
}

Categories