I am trying to input a date in the format dd mm yyyy and have to return in the format e. g. Tuesday, 29th September. I'm new to Java and am not sure if my values from the day, month, year classes are being returned to the main. There is an error for the Date date1 = new Date(day1, month1, year1) saying it is undefined and to make it a constructor. If I make it a constructor and run the program I get values back like lab2.Day#659e0bfd. Not sure where to go from here.
package lab2;
public class Calendar {
//assume all months have 30 days and that 1 January is a Monday;
public static void main(String[] args) { // e.g. input: 29 09 2015
int in1 = Integer.parseInt(args[0]);
int in2 = Integer.parseInt(args[1]);
int in3 = Integer.parseInt(args[2]);
Day day1 = new Day(in1, in2); // string
Month month1 = new Month(in2); // string
Year year1 = new Year(in3); // integer
Date date1 = new Date(day1, month1, year1); //
date1.printName(); // e.g. "The date is Tuesday, 29th of September, 2015
}
}
package lab2;
public class Day {
private int day;
private int month;
private int code;
private String name; //e.g. Tuesday
public Day(int dy, int mth ){
day = dy;
month = mth;
code = ((day*month) % 7);
// Assigning the day variable number to text //
switch (code) {
case 0: name = "Monday";
break;
case 1: name = "Tuesday";
break;
case 2: name = "Wednesday";
break;
case 3: name = "Thursday";
break;
case 4: name = "Friday";
break;
case 5: name = "Saturday";
break;
case 6: name = "Sunday";
break;
default: System.out.println("Incorrect Day Entered");}
}
}
package lab2;
public class Month {
private int month1;
private String monthName;
public Month(int temp1){
month1=temp1;
switch (month1) {
case 1: monthName = "January";
break;
case 2: monthName = "February";
break;
case 3: monthName = "March";
break;
case 4: monthName = "April";
break;
case 5: monthName = "May";
break;
case 6: monthName = "June";
break;
case 7: monthName = "July";
break;
case 8: monthName = "August";
break;
case 9: monthName = "September";
break;
case 10: monthName = "October";
break;
case 11: monthName = "November";
break;
case 12: monthName = "December";
break;
default: System.out.println("Incorrect Month Error");}
}
}
package lab2;
public class Year {
private int yearNumber;
public Year(int temp2)
{
yearNumber=temp2;
}
}
package lab2;
public class Date {
private String day;
private String month;
private int year;
public Date(String temp1, String temp2, int temp3){
day = temp1;
month = temp2;
year = temp3;
}
public void printName() {
System.out.println("The date is " +day+ ", " +month+ ", " +year);
}
}
There is an error for the "Date date1 = new Date(day1, month1, year1)"
saying it is undefined and to make it a constructor.
Since there is no such parameterised constructor in Date class like Date(Day d, Month m, Year y). Its having constructor Date(String temp1, String temp2, int temp3). So parameter types are different.
Instead of
Date date1 = new Date(day1, month1, year1);
use
Date date1 = new Date(day1.name, month1.monthName, year1.yearNumber);
There is an error for the "Date date1 = new Date(day1, month1,
year1)" saying it is undefined and to make it a constructor. If I make
it a constructor and run the program I get values back like
"lab2.Day#659e0bfd". Not sure where to go from here.
You are getting lab2.Day#659e0bfd because you haven't implemented toString() method. Implement toString() method in your Day, Month and Year class and you'll get the desired result. Check the code below-
public class Day {
private int day;
private int month;
private int code;
private String name; //e.g. Tuesday
public Day(int dy, int mth ){
day = dy;
month = mth;
code = ((day*month) % 7);
// Assigning the day variable number to text //
switch (code) {
case 0: name = "Monday";
break;
case 1: name = "Tuesday";
break;
case 2: name = "Wednesday";
break;
case 3: name = "Thursday";
break;
case 4: name = "Friday";
break;
case 5: name = "Saturday";
break;
case 6: name = "Sunday";
break;
default: System.out.println("Incorrect Day Entered");}
}
#Override
public String toString() {
return name;
}
}
Similary, you can put the toString() method in Month class
public class Month {
private int month1;
private String monthName;
public Month(int temp1){
month1=temp1;
switch (month1) {
case 1: monthName = "January";
break;
case 2: monthName = "February";
break;
case 3: monthName = "March";
break;
case 4: monthName = "April";
break;
case 5: monthName = "May";
break;
case 6: monthName = "June";
break;
case 7: monthName = "July";
break;
case 8: monthName = "August";
break;
case 9: monthName = "September";
break;
case 10: monthName = "October";
break;
case 11: monthName = "November";
break;
case 12: monthName = "December";
break;
default: System.out.println("Incorrect Month Error");
#Override
public String toString() {
return monthName;
}
}
Your Year class -
public class Year {
private int yearNumber;
public Year(int temp2)
{
yearNumber=temp2;
}
#Override
public String toString() {
return yearNumber;
}
}
Related
So I've been sitting here for the last 5 hours trying to understand what I'm doing wrong, I have a simple beginners task that is to create multiple different methods to find out a users name which is stored as a global variable, and which month they were born stored as an Integer. Once the Integer has been stored I use a switch statement to correspond to a certain month which I think has went fine so far. However, in calling my methods in my main class I keep getting null value returned for both the UsersName variable and also the monthString variable.
public class BirthMonthWithFunctions {
public static String UsersName;
public static void main(String[] args) {
String monthString = null;
BirthMonthWithFunctions bm = new BirthMonthWithFunctions();
BirthMonthWithFunctions.getUsersName();
bm.getUsersBirthMonthNumber();
BirthMonthWithFunctions.computeBirthMonth(0);
System.out.print(UsersName + "Was born in: " + monthString);
}
static void getUsersName() {
String UsersName = JOptionPane.showInputDialog(null, "What is your name?");
}
public int getUsersBirthMonthNumber() {
int BirthMonth = Integer.parseInt(JOptionPane.showInputDialog(null,"Which month were you born in as an integer between 1-12?"));
return BirthMonth;
}
public static String computeBirthMonth(int BirthMonth) {
int choice = BirthMonth;
String monthString;
switch(choice) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid Month";
break;
}
return monthString;
}
}
Could you please try with this piece of code that I've edited.
public static void main(String[] args) {
String monthString = null;
BirthMonthWithFunctions bm = new BirthMonthWithFunctions();
BirthMonthWithFunctions.getUsersName();
int BirthMonth = bm.getUsersBirthMonthNumber();
BirthMonthWithFunctions.computeBirthMonth(BirthMonth);
System.out.print(UsersName + "Was born in: " + monthString);
}
static void getUsersName() {
UsersName = JOptionPane.showInputDialog(null, "What is your name?");
}
Also remove the String variable declaration from the method : computeBirthMonth
It should be something like :
public static String computeBirthMonth(int BirthMonth) {
int choice = BirthMonth;
switch(choice) {..............
}
return monthString;
}
I am trying to calculate, based on the current day and the number of days in the future a user enters, what day of the week that falls on the calendar. So, for example, today is Friday, or day 5 in my program. If the user enters 15 days ahead, I want it to print that day is Saturday (15 days from today). Unfortunately, I'm getting Friday as the day result no matter how many days ahead are entered. Can someone please help with this? Thank you.
Code so far:
import java.util.*;
import java.text.SimpleDateFormat;
public class DayCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int userEntryInt;
String dayName;
String userEntry;
String weekdayName = new SimpleDateFormat
("EEEE", Locale.ENGLISH).format(System.currentTimeMillis());
System.out.println("Today is "+weekdayName+".");
System.out.println("Please enter how many days in the past or future "+
"of which you'd like to know the day.");
userEntry = sc.next();
userEntryInt = Integer.parseInt(userEntry);
dayName = getDayNumber(weekdayName, userEntryInt);
System.out.println("Your selected day is a " + dayName +".");
}
//method to calculate new day based on user entry
public static String getDayNumber(String name, int userNumber)
{
String dayNumber = "TEST";
int dayResult = 0;
int dayNumberInt;
switch (name){
case "Monday":
dayNumber = "1";
break;
case "Tuesday":
dayNumber = "2";
break;
case "Wednesday":
dayNumber = "3";
break;
case "Thursday" :
dayNumber = "4";
break;
case "Friday":
dayNumber = "5";
break;
case "Saturday":
dayNumber = "6";
break;
case "Sunday":
dayNumber = "7";
}
System.out.println(dayNumber); //test
dayNumberInt = Integer.parseInt(dayNumber);
System.out.println("dayNumberInt is "+dayNumberInt);//test
System.out.println("dayResult is "+dayResult);//test
if(((dayNumberInt+userNumber)/7)<7)
{
dayResult = dayNumberInt+dayResult;
}
else if (((dayNumberInt+userNumber)/7)>7)
{
dayResult = dayNumberInt-dayResult;
}
if (dayResult <0)
{
dayResult = -dayResult;
}
if (dayResult==0)
{
dayResult = dayNumberInt;
}
String dayNameResult="";
switch (dayResult){
case 1: dayNameResult = "Monday";
break;
case 2: dayNameResult = "Tuedsay";
break;
case 3: dayNameResult = "Wednesday";
break;
case 4: dayNameResult = "Thursday";
break;
case 5: dayNameResult = "Friday";
break;
case 6: dayNameResult = "Saturday";
break;
case 7: dayNameResult = "Sunday";
break;
}
return (dayNameResult);
}
}
What you want to do is take the day of the week it currently is and change it to a number then take that number and add it to the number that the user provided. Then you divide by 7 and find the remainder.
Note:
% is the remainder operator. 10%3=1, 5%3=2, 100%10=0.
For Example:
The day of the week is Monday so that days value would be 1. The user enters 9 so you add 1 and 9 together to get 10. The remainder of dividing 10 by 7 is 3 so the day of the week would be Wednesday.
public static getDayNumber(String name, int userNumber){
if(userNumber<1)
return "Invalid Number";
int dayNumber = 0;
switch(name){
case "Monday":
dayNumber = 1;
break;
case "Tuesday":
dayNumber = 2;
break;
case "Wednesday":
dayNumber = 3;
break;
case "Thursday" :
dayNumber = 4;
break;
case "Friday":
dayNumber = 5;
break;
case "Saturday":
dayNumber = 6;
break;
case "Sunday":
dayNumber = 7;
}
dayNumber = (dayNumber + userNumber)%7;
switch (dayNumber){
case 1: return "Monday";
break;
case 2: return "Tuedsay";
break;
case 3: return "Wednesday";
break;
case 4: return "Thursday";
break;
case 5: return "Friday";
break;
case 6: return "Saturday";
break;
case 7: return "Sunday";
break;
default: return "Invalid Day Provided";
}
}
using hashmap
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
public class Solution {
public static void main(String[] args) {
String resultDay=new Solution().solution("Sat",23);
System.out.println(resultDay);
}
public String solution(String S, int K) {
int day = getday(K);
int cDay = listofdays.get(S);
cDay = day + cDay;
cDay = cDay % 7;
return getDayOfWeek(cDay);
}
public static Map<String, Integer> listofdays;
static {
listofdays = new LinkedHashMap<>();
listofdays.put("Sun", 1);
listofdays.put("Mon", 2);
listofdays.put("Tue", 3);
listofdays.put("Wed", 4);
listofdays.put("Thur", 5);
listofdays.put("Fri", 6);
listofdays.put("Sat", 7);
}
static int getday(int k) {
return k % 7;
}
private String getDayOfWeek(int value) {
for (Entry<String, Integer> entry : listofdays.entrySet()) {
if (entry.getValue().equals(value)) {
return entry.getKey();
}
}
return "";
}
}
Im trying to get my program to print out the day of any given date using functions that I have to write and declare, although for the early dates of the month the program doesnt seem to print the write day. The equation in the dayOfTheWeek function, w, was given to us to calculate for the day, although for the 'floor' code to be used i had to create another 'private static' function for reasons im not quite sure of, any reason as to why would be great as well as any reason for why my program isnt returning the right day for certain dates.
here's my code, any help would be greatly appreciated :)
import java.util.Scanner;
import javax.swing.JOptionPane;
public class DayOfTheWeek {
public static final int SEPTEMBER_APRIL_JUNE_NOVEMBER_DAYS = 30;
public static final int REST_OF_YEAR_DAYS = 31;
public static final int LEAP_YEAR_FEB = 29;
public static final int NORMAL_FEB = 28;
public static final int MONTHS = 12;
public static void main(String[] args) {
try
{
String input = JOptionPane.showInputDialog("Enter date (day/month/year):");
Scanner scanner = new Scanner( input );
scanner.useDelimiter("/");
int day = scanner.nextInt();
int month = scanner.nextInt();
int year = scanner.nextInt();
scanner.close();
String numberEnding = numberEnding (day);
String dayEnding = day + numberEnding;
String monthName = monthName (month);
String dayName = dayOfTheWeek (day, month, year);
if (validDate(day, month, year))
{
JOptionPane.showMessageDialog(null, dayName + " " + dayEnding + " " + monthName
+ " " + year + " is a valid date.");
}
else
{
JOptionPane.showMessageDialog(null, "" + dayEnding + " " + monthName
+ " " + year + " is not a valid date.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
catch (NullPointerException exception)
{
}
catch (java.util.NoSuchElementException exception)
{
JOptionPane.showMessageDialog(null, "No number entered. \nPlease restart and try again.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
public static boolean validDate( int day, int month, int year ) {
return ((year >= 0) && (month >= 1) && (month <= MONTHS) &&
(day >= 1) && (day <= daysInMonth( month, year )));
}
public static int daysInMonth( int month, int year ) {
int monthDays;
switch (month)
{
case 2:
monthDays = isLeapYear(year) ? LEAP_YEAR_FEB : NORMAL_FEB;
break;
case 4:
case 6:
case 9:
case 11:
monthDays = SEPTEMBER_APRIL_JUNE_NOVEMBER_DAYS;
break;
default:
monthDays = REST_OF_YEAR_DAYS;
}
return monthDays;
}
public static boolean isLeapYear( int year ) {
return (((year%4 == 0) && (year%100 != 0)) || (year%400 == 0));
}
public static String numberEnding( int day ) {
String dayEnding = "";
int remainder = day%10;
if (day >= 10 && day <= 20)
{
dayEnding = "th";
}
else
{
switch (remainder)
{
case 1:
dayEnding = "st";
break;
case 2:
dayEnding = "nd";
break;
case 3:
dayEnding = "rd";
break;
default:
dayEnding = "th";
break;
}
}
return dayEnding;
}
public static String monthName( int month ) {
String monthName = "";
switch (month)
{
case 1:
monthName = "January";
break;
case 2:
monthName = "February";
break;
case 3:
monthName = "March";
break;
case 4:
monthName = "April";
break;
case 5:
monthName = "May";
break;
case 6:
monthName = "June";
break;
case 7:
monthName = "July";
break;
case 8:
monthName = "August";
break;
case 9:
monthName = "September";
break;
case 10:
monthName = "October";
break;
case 11:
monthName = "November";
break;
case 12:
monthName = "December";
break;
default:
}
return monthName;
}
public static String dayOfTheWeek (int day, int month, int year){
String dayName = "";
int Y;
if (month == 1 || month == 2)
{
Y = (year-1);
}
else
{
Y = (year);
}
int y = Y%100;
int c = Y/100;
int w = (day + floor(2.6 * (((month+9) % 12)+ 1) -0.2)
+ y + floor(y/4) + floor(c/4) - (2*c));
w = (w%7);
if (w < 0)
{
w += 7;
}
switch (w)
{
case 0:
dayName = "Sunday";
break;
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
}
return dayName;
}
private static int floor(double d) {
return 0;
}
}
I believe you need to use the Math.floor() method. Simply call this in place of your floor method:
(day + Math.floor(2.6 * (((month+9) % 12)+ 1) -0.2)
+ y + Math.floor(y/4) + Math.floor(c/4) - (2*c));
You can also cast the equation directly using (int):
int w = (int) (day + 2.6 * ((month+9) % 12 + 1) - 0.2 + y + (y/4) + (c/4) - (2*c));
However, in your case I think that the values will be rounded improperly using casting, so you should probably use the floor method.
If you'd like some additional information on the differences between floor and casting here's a stackoverflow question that addresses it: Cast to int vs floor
I would use the Joda-Time library.
import org.joda.time.DateTime
final DateTime date = new DateTime();
final int dayOfWeek = date.getDayOfWeek();
See the Joda-Time User Guide for more info and examples..
public class Methods extends javax.swing.JFrame implements Method_Interface {
protected Map<String, User> userMap = new TreeMap<>();
protected String username, password;
protected boolean loggedIn;
public void fillUserMap() {
//Some code:
}
}
Code for initializing values to the MAP:
public void fillUserMap() {
String race = "";
String month, gender;
int m, age, day, year;
for (Forms.Users u : usersList) {
month = "";
gender = "";
switch (u.getGender()) {
case 0:
gender = "Male";
break;
case 1:
gender = "Female";
break;
}
switch (u.getRace()) {
case 0:
race = "White";
break;
case 1:
race = "Black";
break;
case 2:
race = "Coloured";
break;
case 3:
race = "Indian";
break;
case 4:
race = "Other";
}
day = Integer.parseInt(u.getDateOfBirth().trim().substring(0, 2));
year = Integer.parseInt(u.getDateOfBirth().trim().substring(6, 10));
age = 2014 - year;
m = Integer.parseInt(u.getDateOfBirth().trim().substring(3, 5));
switch (m) {
case 1:
month = "January";
break;
case 2:
month = "February";
break;
case 3:
month = "March";
break;
case 4:
month = "April";
break;
case 5:
month = "May";
break;
case 6:
month = "June";
break;
case 7:
month = "July";
break;
case 8:
month = "August";
break;
case 9:
month = "September";
break;
case 10:
month = "October";
break;
case 11:
month = "November";
break;
case 12:
month = "December";
break;
}
if (u.getUserid().substring(0, 2).equals("#D")) {
try{
int get = donorInfoList.indexOf(u.getUserid());
get++;
DonorInfo d = donorInfoList.get(get);
Blood_Donor temp = new Blood_Donor(bloodType(u), d.getTimesDonated().toString(), u.getWeight(), u.getUserid(), u.getPassword(), u.getFirstname(), u.getSurname(), day, month, year, u.getEmail(), gender, race, age);
for (DonorInfo dTemp : donorInfoList) {
if (dTemp.getUserid().equals(u.getUserid())) {
temp.setWeight(u.getWeight());
temp.setUnits(dTemp.getTimesDonated().toString());
temp.setBloodType(bloodType(u));
userMap.put(temp.getuName(), temp);
}
}
} catch(Exception e) {
System.out.println(e);
}
} else if (u.getUserid().substring(0, 2).equals("#C")) {
int get = clientsList.indexOf(u.getUserid()+1);
Clients c = clientsList.get(get);
Client temp = new Client(c.getDebt(), u.getWeight(), bloodType(u), u.getUserid(), u.getPassword(), u.getFirstname(), u.getSurname(), day, month, year, u.getEmail(), gender, race, age);
for (Clients cTemp : clientsList) {
Map<Integer, String> products = new TreeMap<>();
if (cTemp.getClientsPK().getUserid().equals(u.getUserid())) {
for (Clients cTemp2 : clientsList) {
int i = 0;
if (cTemp2.getClientsPK().getUserid().equalsIgnoreCase(u.getUserid())) {
for (int j = 0; j < cTemp2.getQuantity(); j++) {
if (cTemp2.getQuantity() == 1) {
products.put(i++, cTemp2.getClientsPK().getProductId());
break;
} else {
products.put(i++, cTemp2.getClientsPK().getProductId());
}
}
}
}
temp.setProducts(products);
userMap.put(temp.getuName(), temp);
}
}
} else if (u.getUserid().substring(0, 2).equals("#S")) {
User temp = new User(u.getUserid(), u.getPassword(), u.getFirstname(), u.getSurname(), day, month, year, u.getEmail(), gender, race, age);
userMap.put(u.getUserid(), temp);
}
}
}
Child JFrame:
public final class Log_In extends Methods {
//some code
}
I run the fillUserMap method in the parent JFrame i.e Methods before trying to get those values back in one of my child JFrames. But when I search for values in my treemap I dont find any
My class built to output the Month and month number builds and runs fine, but somewhere in my class my monthString is just being assigned null. I cannot see where I have ran into this mistake, and I apologize for my bad code. TY! ~~~
public class MonthClass
{
private int monthNum;
private String monthString;
public MonthClass(int num)
{
monthNum = num;
monthString = monthName(num);
}
public void setmonthNum(int num)
{
monthNum = num;
monthString = monthName(num);
}
public String getmonthName(int num)
{
switch (num)
{
case 1: monthString = "January";
break;
case 2: monthString = "Febuary";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString= "Augest";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "This is not a month, re-enter a number";
break;
}
return monthString;
}
public String monthName(int num)
{
return monthString;
}
public String toString()
{
return "The month number is " + monthNum + " and the month name is " + monthString;
}
}
The problem is that your code at no place modifies monthString, and its value always remains null (default value for reference types).
Instead of monthName you should be calling getmonthName (the conversion from month number to string is happening there):
monthString = getmonthName(num);
Method monthName is only a getter - it doesn't modify the monthString. Also as this method doesn't make use of any argument, you can possibly get rid of that too:
public String monthName() {
return monthString;
}
Also, in the default case in the switch statement, the assignment of non-month string is going to happen silently. You might want to print something on the console as well.