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")){
Related
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.
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
My code compiles well, except when displaying the inputted info, i am getting an error i dont understand:
**Exception in thread "main" java.lang.NullPointerException
at Employee.(Employee.java:18)
at unit11.main(unit11.java:50)**
My Code is attached below.
public class Employee {
public Name name;
public Date date;
public Address address;
public String[] data;
public Employee(String first, String last,
int inMont, int inDay, int inYear,
String inStreet, String inCity, String inState, String inZip){
if (errorCheck(inMont, inDay, inYear, inState, inZip) == 1)
System.out.println("Error in data. Please try again.");
else{
name = new Name(first, last);
date = new Date(inMont, inDay, inYear);
address = new Address(inStreet, inCity, inState, inZip);
data[0] = name.firstName + " " + name.lastName;
data[1] = date.month + " " + date.day + ", " + date.year;
data[2] = address.street + ", " + address.city + ", " + address.state + ", " + address.zip;
}
}
public int errorCheck(int inMonth, int inDay, int inYear,String inState, String inZip){
if(inMonth < 1 || inMonth > 12 || inYear < 1000 ||
inDay < 1 || inDay > 31 ||
((inMonth == 4 || inMonth == 6 || inMonth == 9 || inMonth == 11) && inDay > 30)
|| (inMonth == 2 && inDay > 29) || inState.length() != 2)
return 1;
else return 0;
}
}
//and line 50 in the unit11 code( is the employees[i] part)
if(errorCheck(month, day, year, state, zip) ==1)
System.out.println("Invalid data input. Please try again.");
else{
employees[i] = new Employee(firstName, lastName, month, day, year, street, city, state, zip);
i++;
}
Your constructor is expecting inZip to be an int:
public Employee(String first, String last,
int inMont, int inDay, int inYear,
String inStreet, String inCity, String inState, int inZip)
But it's a String:
String zip = input.nextLine();
Postal codes aren't integers, they're strings. Change the constructor/class/etc. to expect a string.
a program which has one method that takes int "Year" as a parameter which then based on the parameter figures out whether it is a leap year or not. Theyve given a table showing which is not and which is a leap year
2010 /4 = no .. /100 = no .. /400 = no .. leap = no
2012 /4 = yes .. /100 = no .. /400 = no .. leap = yes
1900 /4 = yes .. /100 = yes .. /400 = no .. leap = no
2000 /4 = yes .. /100 = yes .. /400 = yes .. leap = yes
They also want the method to identify if a year is before the gregorian calendar 1565
Below is the current code I have done. It works for some years and doesnt for others. Obviously im doing something wrong. Any help would be greatly appreaciated if someone could inform me what Im doing right and what Im doing wrong or how best to go about this?
public class theleapyear{
public static void main( String [] args){
leapyear(2010);
leapyear(2012);
leapyear(1900);
leapyear(2000);
leapyear(1565);
}
public static void leapyear( int year){
if (year < 1565)
System.out.println( year + ":" + " predates the Gregorian Calendar ");
else
if (year % 4 != 0)
if (year % 100 != 0)
if (year % 400 != 0)
{
System.out.println( year + ":" + " is not a leap year ");
}
else
{
if (year % 4 == 0)
if (year % 100 != 0)
if (year % 400 != 0)
System.out.println( year + ":" + " is a leap year ");
}
else
{
if (year % 4 == 0)
if (year % 100 == 0)
if (year % 400 != 0)
System.out.println( year + ":" + " is not a leap year ");
}
else
{
if (year % 4 == 0)
if (year % 100 == 0)
if (year % 400 == 0)
System.out.println( year + ":" + " is a leap year ");
}
}
}
You repeat a lot of code; try resuming it using comparators.
public class theleapyear{
public static void main( String [] args){
leapyear(2010);
leapyear(2012);
leapyear(1900);
leapyear(2000);
leapyear(1565);
}
public static void leapyear( int year){
if (year < 1565)
System.out.println( year + ":" + " predates the Gregorian Calendar ");
else
{
if ((year%4 != 0){
System.out.println(year + ":" + " is not a leap year ");
}
else {
if((year%100==0 && year%400==0)||(year%100!=0 && year%400!=0){
System.out.println(year + ":" + " it is a leap year ");
}
else {
System.out.println(year + ":" + " is not a leap year ");
}
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));
// ...
}