I need to create a program which shows the day of week, when you enter the specific date to console.
Here's the code I've written, but still not working, why would it be?
public class CalculateDay{
public static void main(String []args){
int m = Integer.parseInt(args[0]);
int d = Integer.parseInt(args[1]);
int y = Integer.parseInt(args[2]);
System.out.println("Finding day of week for "+m+"-"+d+"-"+y);
int yo = y - ((14-m)/12);
int x = yo + yo/4 - yo/100 + yo/400;
int mo = m + 12*((14-m)/12) -2;
int dayOfWeek = (d + x + (31*mo)/12)%7;
String dayString;
switch(dayOfWeek){
case 0: dayString = "Sunday";
break;
case 1: dayString = "Monday";
break;
case 2: dayString = "Tuesday";
break;
case 3: dayString = "Wednesday";
break;
case 4: dayString = "Thursday";
break;
case 5: dayString = "Friday";
break;
case 6: dayString = "Saturday";
break;
default: dayString = "Could not find";
}
System.out.println(dayString);
}
}
Try this:
int m = Integer.parseInt(args[0]);
int d = Integer.parseInt(args[1]);
int y = Integer.parseInt(args[2]);
System.out.println("Finding day of week for "+m+"-"+d+"-"+y);
Calendar cal = new GregorianCalendar(y, m, d);
System.out.println("DAY_OF_WEEK: " + cal.get(Calendar.DAY_OF_WEEK));
Related
I am having difficulty with a java problem I am attempting to make,
I am very new and still learning if anyone can spot what I am doing wrong I would appreciate any help.
I am attempting to have the user type in a year from 2000 to 2016 and the output would be the players statistics.
Thank You
import java.util.Scanner;
public class NflPlayers{
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a Year (2000-2016): " );
String year = input.next();
input.close();
if (yearNumber(year) == 0) {
System.out.println("Year 2000-2016");
System.out.println("Invalid year input.");
System.exit(0);
}
System.out.println(year + " Passing touchdowns");
}
int getNumberOfPasses(int year) {
switch (yearNumber(null)) {
case 1: return 28;
case 2: return 36;
case 3: return 33;
case 4: return 25;
case 5: return 34;
case 6: return 39;
case 7: return 36;
case 8: return 28;
case 9: return 0;
case 10: return 50;
case 11: return 24;
case 12: return 26;
case 13: return 28;
case 14: return 23;
case 15: return 28;
case 16: return 18;
case 17: return 0;
default: return 0;
}
}
public static int yearNumber(String year) {
int yearNumber;
switch (year){
case"2016":
yearNumber = 1;
break;
case"2015":
yearNumber = 2;
break;
case"2014":
yearNumber = 3;
break;
case"2013":
yearNumber = 4;
break;
case"2012":
yearNumber = 5;
break;
case"2011":
yearNumber = 6;
break;
case"2010":
yearNumber = 7;
break;
case"2009":
yearNumber = 8;
break;
case"2008":
yearNumber = 9;
break;
case"2007":
yearNumber = 10;
break;
case"2006":
yearNumber = 11;
break;
case"2005":
yearNumber = 12;
break;
case"2004":
yearNumber = 13;
break;
case"2003":
yearNumber = 14;
break;
case"2002":
yearNumber = 15;
break;
case"2001":
yearNumber = 16;
break;
case"2000":
yearNumber = 17;
break;
default:
yearNumber = 0;
break;
}
return yearNumber;
}
}
You ca use do{}while() loop instead for example :
Scanner input = new Scanner(System.in);
String year;
boolean pass = false;
do {
System.out.print("Enter a Year (2000-2016): ");
year = input.next();
try {
if (Integer.parseInt(year) >= 2000 && Integer.parseInt(year) <= 2006) {
System.out.println("true");
pass = true;
}
} catch (NumberFormatException e) {
System.out.println("Not correct try again");
}
} while (!pass);
So if the user enter a year between 2000 and 2006 you can pass, else repeat again until the user enter the correct year.
I've run your code and examined it.
It appears you've left out a method call for getNumberOfPasses(), which is the main problem I can tell.
with System.out.println(year + " Passing touchdowns"); you don't actually want the year displayed, i believe the correct code you're looking for is:
System.out.println(getNumberOfPasses(yearNumber(year)) + " Passing touchdowns");
This will run through both methods to display the info you need. However, you will need to fix the method header of int getNumberOfPasses(int year) to static int getNumberOfPasses(int year)
Furthermore, you could eliminate one of the methods entirely and just have the return values for passes tied to the year you input. Rather than passing digits from 1-17 to another method.
Hope this helps and good luck with your projects!
I need to write a Java program (class NextDay) that calculates and prints the date of the next day by entering the day, month, and year.
Sample call and output:
Actual Date 12.12.2004
The next day is the 13.12.2004.
The input should also be checked for correctness! If an erroneous date constellation (e.g., 32 12 2007) has been entered, the exception InvalidDateArgumentsException is to be thrown. Define this class in a suitable form as a subclass of the class java.lang.Exception.
I started to creating it but the problem is; i cant tell that < or > in switch statements.What should i do? Here are my classes:
public class Date {
private int day;
private int month;
private int year;
public Date(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
public Date getNextDay() throws Exception {
if (isLeapYear() == true) {
switch (month) {
case 1:
day = 31;
break;
case 2:
day = 29;
break;
case 3:
day = 31;
break;
case 4:
day = 30;
break;
case 5:
day = 31;
break;
case 6:
day = 30;
break;
case 7:
day = 31;
break;
case 8:
day = 31;
break;
case 9:
day = 30;
break;
case 10:
day = 31;
break;
case 11:
day = 30;
break;
case 12:
day = 31;
break;
}
}
return new Date(day + 1, month, year);
}
public int getDay() {
return day;
}
public int getMonth() {
return month;
}
public int getYear() {
return year;
}
public boolean isLeapYear() {
if (year % 4 == 0 && year % 100 != 0 && year % 400 == 0) {
return true;
}
return false;
}
public String toString() {
return this.day + "." + this.month + "." + this.year;
}
}
...
public class NextDay {
public static void main(String args[]) throws Exception {
Date dateObj = new Date(20, 5, 2016);
System.out.println("Old Date: " + dateObj.getDay() + "." + dateObj.getMonth() + "." + dateObj.getYear() + ".");
System.out.println("The next day is " + dateObj.getNextDay().toString() + ".");
}
}
You are saying that you want an "or" statement inside switch, right? If you write case labels line by line you get "or statement", like this:
switch(variable){
case 1:
case 2:
case 3: {
//.. when variable equals to 1 or 2 or 3
}
}
So that, you can write your getMaxDaysInMonth method like this:
int getMaxDaysInMonth()
{
int daysInMonth = 0;
switch(month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
daysInMonth = 31;
break;
case 2:
if(isLeapYear())
{
daysInMonth = 29;
}
else
{
daysInMonth = 28;
}
break;
case 4:
case 6:
case 9:
case 11:
daysInMonth = 30;
}
return daysInMonth;
}
Also, you are checking for the leap year incorrectly. Here's the correct way:
boolean isLeapYear(){
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
And here's how you increment a day:
void incrementDate(){
if((day + 1) > getMaxDaysInMonth())
{
day = 1;
if (month == 12)
{
month = 1;
year++;
}else{
month++;
}
} else {
day++;
}
}
EDIT since we can't just use standard classes
If you have to use switch case, you should use it to set max day in current month and then check, if your current day more than this max day:
int maxDay;
switch (month) {
case 1: maxDay = 31; break;
case 2: maxDay = isLeapYear() ? 29 : 28; break;
case 3: maxDay = 31; break;
// ... other months ...
case 12: maxDay = 31; break;
default: throw new InvalidDateArgumentsException();
}
if (isLeapYear()) {
maxDay = 29;
}
if (day > maxDay) {
throw new InvalidDateArgumentsException();
}
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 "";
}
}
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;
}
}
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..