Java Code Logic Error - java

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

Related

Updating Date inside a while loop, 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.

How can I take the values that are made inside the iterations of the for loop and use them outside of it but in the same method?

I want to be able to take the values out of the for loop as well as make individual values for the separate iterations of the for loop so that I can put them into the comparison if/else statements below the for loop.
public static void calculateBirthdays(Scanner console) {
//Print purpose
System.out.println("This program compares two birthdays");
System.out.println("and displays which one is sooner.");
Calendar cal = Calendar.getInstance();
int todayYear = cal.get(Calendar.YEAR);
int todayMonth = cal.get(Calendar.MONTH)+1;
int todayDay = cal.get(Calendar.DAY_OF_MONTH);
SimpleDateFormat d = new SimpleDateFormat();
int todayDayValue = absDayVal(todayMonth, todayDay, todayYear);
System.out.println("Today is " + d.format(cal.getTime()) + ", day #" + todayDayValue + " of the year.");
for (int i = 1; i <= 2; i++) {
System.out.println("Person " + i + ":\nWhat month, day and year were you born?");
int month = console.nextInt();
int day = console.nextInt();
int year = console.nextInt();
int daysPassed = absDayVal(month, day, year);
int daysInYear = leapYear(todayYear);
int daysUntilBday = daysAway(daysPassed, todayDayValue, daysInYear);
DecimalFormat df = new DecimalFormat("0.##");
System.out.println(month + "/" + day + "/" + todayYear + " falls on day #" + todayDayValue + " of " + daysInYear + ".");
if(todayDayValue == daysPassed){
System.out.println("Happy birthday!");
} else if (todayDayValue != daysPassed){
System.out.println("Your next birthday is in " + daysUntilBday + " day(s).");
System.out.println("That is " + df.format((percentUntil(daysUntilBday, daysInYear)) * 100) + " percent of a year away.");
}
}
if(percent < percent) {
System.out.println("Person 1's birthday is sooner.");
} else if (percent < percent) {
System.out.println("Person 2's birthday is sooner.");
} else if (percent == percent) {
System.out.println("Wow, you share the same birthday!");
}
}
You can simply declare them outside of the loop like this.
int month;
int day;
int year;
for (int i = 1; i <= 2; i++) {
System.out.println("Person " + i + ":\nWhat month, day and year were you born?");
month = console.nextInt();
day = console.nextInt();
year = console.nextInt();
...
}
This concept is known as scope. Here is an article that might give you a better understanding on variable scope.

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

Cannot get my program to properly read in file to execute methods

In the following code, I'm having problems getting each part of the program to run the respective methods. Individually testing them, they work fine. However, I don't think the fileIn.next() is working how I need it to to get the letters and numbers to appear in order for the right statement to run. Often, I'll get a NoSuchElementException and I cannot figure out what steps I need to take to fix it.
Edit 1: Sorry if the formatting is getting wonky, but I added the class I had to create with the methods I mentioned. I also noticed after one iteration, the letters in my file stop appearing somehow?
import java.util.*;
import java.io.*;
public class p2{
public static void main(String[] args) throws IOException{
Date date1 = new Date();
Date date2 = new Date();
Date date3 = new Date(5, 31, 2016);
System.out.println();
Scanner fileIn = new Scanner(new File("test1.txt"));
while (fileIn.next() != null ){
if (fileIn.next().equals("G") && fileIn.next().equals("1")){
date1.getDate();
}
if (fileIn.next().equals("G") && fileIn.next().equals("2")){
date2.getDate();
}
if (fileIn.next().equals("G") && fileIn.next().equals("3")){
date3.getDate();
}
if (fileIn.next().equals("I") && fileIn.nextInt() == 1){
date1.incrementDay();
}
if (fileIn.next().equals("I") && fileIn.nextInt() == 2){
date2.incrementDay();
}
if (fileIn.next().equals("I") && fileIn.nextInt() == 3){
date3.incrementDay();
}
if (fileIn.next().equals("D") && fileIn.nextInt() == 1){
date1.displayDate();
}
if (fileIn.next().equals("D") && fileIn.nextInt() == 2){
date2.displayDate();
}
if (fileIn.next().equals("D") && fileIn.nextInt() == 3){
date3.displayDate();
}
if (fileIn.next().equals("S") && fileIn.nextInt() == 1){
String newDate = fileIn.next();
//System.out.println("newDate: " + newDate);
int num1 = Integer.parseInt(newDate.substring(0, 2));
int num2 = Integer.parseInt(newDate.substring(3, 5));
int num3 = Integer.parseInt(newDate.substring(6, 10));
System.out.println(num1 + "/" + num2 + "/" + num3);
date1.setDate(num1, num2, num3);
}
if (fileIn.next().equals("S") && fileIn.nextInt() == 2){
String newDate = fileIn.next();
//System.out.println("newDate: " + newDate);
int num1 = Integer.parseInt(newDate.substring(0, 2));
int num2 = Integer.parseInt(newDate.substring(3, 5));
int num3 = Integer.parseInt(newDate.substring(6, 10));
System.out.println(num1 + "/" + num2 + "/" + num3);
date2.setDate(num1, num2, num3);
}
if (fileIn.next().equals("S") && fileIn.nextInt() == 3){
String newDate = fileIn.next();
//System.out.println("newDate: " + newDate);
int num1 = Integer.parseInt(newDate.substring(0, 2));
int num2 = Integer.parseInt(newDate.substring(3, 5));
int num3 = Integer.parseInt(newDate.substring(6, 10));
System.out.println(num1 + "/" + num2 + "/" + num3);
date3.setDate(num1, num2, num3);
}
if (fileIn.next().equals("Q")){
System.exit(0);
}
}
System.out.println("p2 complete");
fileIn.close();
}
}
class Date{
private int month;
private int day;
private int year;
public Date(){
this.month = 1;
this.day = 1;
this.year = 2000;
System.out.println("Empty constructor created.");
}//end Date constructor
public Date(int month, int day, int year){
this.month = month;
this.day = day;
this.year = year;
System.out.println("Overload constructor created.");
}//end Date overload constructor
public void setDate(int month, int day, int year){
//System.out.println("setDate activated: ");
this.month = month;
this.day = day;
this.year = year;
//System.out.println("setDate complete.");
}//end setDate
public void getDate(){
if (month < 10 && !(day < 10)){//if month is the only single digit int
System.out.println("getDate activated: 0" + month + "/" + day + "/" + year);
}//end if
else if (day < 10 && month > 10){//if day is the only single digit int
System.out.println("getDate activated: " + month + "/0" + day + "/" + year);
}//end else if
else if (day < 10 && month < 10){//if both month and day are single digit ints
System.out.println("getDate activated: 0" + month + "/0" + day + "/" + year);
}//end else if
else{
System.out.println("getDate activated: " + month + "/" + day + "/" + year);
}//end else
}//end getDay
public void incrementDay(){
//System.out.println("Test incrementDay: ");
int[] daysPerMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (year % 4 == 0){
daysPerMonth[1] = 29;
}//end if
for (int i = 0; i < 12; i++){
if (i+1 == month && day == daysPerMonth[i]){//if we find the month and day is at the end of the month
if (month == 12 && day == 31){//if we are at december 31st
month = 1;
day = 1;
year += 1;
break;
}//end
else{
month += 1;
day = 1;
break;
}//end else
}//end if
else if (i+1 == month && day < daysPerMonth[i]){
day += 1;
break;
}//end else if
else{
}//end else
}//end for
setDate(month, day, year);
System.out.print("Result of successful increment: ");
getDate();
}//end incrementDay
public void displayDate(){
System.out.print("displayDate activated: ");
System.out.println(this.month + "/" + this.day + "/" + this.year);
}
}//end Date
EVERY next removes one token, so if (fileIn.next().equals("G") && fileIn.next().equals("1")){ reads two tokens if the first token equals G otherwise the if will fail on the first part and NOT read read the second next
So you are better off to put the tokens into variables, like
String tok1 = fileIn.next ();
String tok2 = fileIn.next ();
if (tok1.equals("G") && tok2.equals("1")){

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