Is there a more efficient way to do this? | Month conversion - java

I was given a little task to complete where a user would be asked to input either a month or the numerical equivalent and it would return the numerical value of the entered month, or the month corresponding to the inputted numerical value. The constraints are as follows:
- It must not contain a GUI of any kind
- I have to use the BufferedReader for input
- I have to use at least one Switch statement
If anyone has any ideas, it would be greatly appreciated.
My code so far is as follows:
/**
* Month task
*
* #author Dan Foad
* #version 0.01
*/
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Months {
public static void main(String []args) throws IOException {
int iInput;
boolean isParseable;
String szInput;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please type either the number of the month, or the month itself to convert.");
System.out.print("> ");
szInput = br.readLine();
try {
Integer.valueOf(szInput);
isParseable = true;
}
catch(Exception e) {
isParseable = false;
}
if (isParseable) {
iInput = Integer.valueOf(szInput);
System.out.println(numberToMonth(iInput));
}
else {
szInput = szInput.toLowerCase();
System.out.println(monthToNumber(szInput));
}
return;
}
public static String numberToMonth(int iMonth) {
String MonthReturn;
switch(iMonth) {
case (1): MonthReturn = "January"; break;
case (2): MonthReturn = "February"; break;
case (3): MonthReturn = "March"; break;
case (4): MonthReturn = "April"; break;
case (5): MonthReturn = "May"; break;
case (6): MonthReturn = "June"; break;
case (7): MonthReturn = "July"; break;
case (8): MonthReturn = "August"; break;
case (9): MonthReturn = "September"; break;
case (10): MonthReturn = "October"; break;
case (11): MonthReturn = "November"; break;
case (12): MonthReturn = "December"; break;
default: MonthReturn = "0"; break;
}
return MonthReturn;
}
public static int monthToNumber(String szMonth) {
int MonthReturn;
switch(szMonth) {
case ("january"): MonthReturn = 1; break;
case ("february"): MonthReturn = 2; break;
case ("march"): MonthReturn = 3; break;
case ("april"): MonthReturn = 4; break;
case ("may"): MonthReturn = 5; break;
case ("june"): MonthReturn = 6; break;
case ("july"): MonthReturn = 7; break;
case ("august"): MonthReturn = 8; break;
case ("september"): MonthReturn = 9; break;
case ("october"): MonthReturn = 10; break;
case ("november"): MonthReturn = 11; break;
case ("december"): MonthReturn = 12; break;
default: MonthReturn = 0; break;
}
return MonthReturn;
}
}

How about this?
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Calendar;
import static java.util.Calendar.APRIL;
import static java.util.Calendar.AUGUST;
import static java.util.Calendar.DECEMBER;
import static java.util.Calendar.FEBRUARY;
import static java.util.Calendar.JANUARY;
import static java.util.Calendar.JULY;
import static java.util.Calendar.JUNE;
import static java.util.Calendar.MARCH;
import static java.util.Calendar.MAY;
import static java.util.Calendar.NOVEMBER;
import static java.util.Calendar.OCTOBER;
import static java.util.Calendar.SEPTEMBER;
public class Months {
public static void main(String []args) throws IOException {
Integer iInput = null;
String szInput = null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please type either the number of the month, or the month itself to convert.");
System.out.print("> ");
szInput = br.readLine();
boolean wasInt = false;
try {
iInput = Integer.valueOf(szInput);
System.out.println(numberToMonth(iInput));
wasInt = true;
}
catch(Exception e) {
}
if (! wasInt) {
szInput = szInput.toLowerCase();
System.out.println(monthToNumber(szInput));
}
return;
}
public static String numberToMonth(int iMonth) {
switch(iMonth-1) {
case (JANUARY): return "January";
case (FEBRUARY): return "February";
case (MARCH): return "March";
case (APRIL): return "April";
case (MAY): return "May";
case (JUNE): return "June";
case (JULY): return "July";
case (AUGUST): return "August";
case (SEPTEMBER): return "September";
case (OCTOBER): return "October";
case (NOVEMBER): return "November";
case (DECEMBER): return "December";
}
return "Unknown";
}
public static int monthToNumber(String szMonth) {
if (szMonth == null) {
return 0;
}
switch(szMonth.toLowerCase()) {
case ("january"): return 1 + JANUARY;
case ("february"): return 1 + FEBRUARY;
case ("march"): return 1 + MARCH;
case ("april"): return 1 + APRIL;
case ("may"): return 1 + MAY;
case ("june"): return 1 + JUNE;
case ("july"): return 1 + JULY;
case ("august"): return 1 + AUGUST;
case ("september"): return 1 + SEPTEMBER;
case ("october"): return 1 + OCTOBER;
case ("november"): return 1 + NOVEMBER;
case ("december"): return 1 + DECEMBER;
}
return 0;
}
}

You can also do this:
private static final String[] monthNames = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
public static String numberToMonth(int iMonth) {
return (iMonth < 12 && iMonth > 0) ? monthNames[iMonth - 1] : "None";
}

You can add the strings "1","2","3", ..., "12" to your monthToNumber method, that way you won't have to convert the user input to Integer using String.valueOf.

Yeah in the number to month method you can just create a String array with the names of the months in chronological order and then just fetch the string at the index of the given input value minus 1

Related

How to fix inputting the user's info twice?

The program ask for a month and it could be a string or int. In the isDigitsOrSpecial method, it works and it has the same format in my method isString. The difference is that when I want to enter the month in a string way (ex.january), it will ask me twice. So, I don't know what to do. I tried a lot of ways but it doesn't work. Do you have any suggestions?
Here's my full code. You can try to run it, and see the problem where you have to input twice the name of the month in a string way.
I would really appreciate any of your suggestions.
package Electronic_payment_process;
import java.util.InputMismatchException;
import java.util.Scanner;
public class practice {
static String s;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
float current = 0, recent = 0, difference, multiply;
String month, recents, currents = null;
System.out.println("The month could be a number or a name.");
System.out.println("Example: (01-12) or (JAN – dec)");
// for the validation of due month user’s input
do {
System.out.print("\nEnter a month: ");
month = scan.next();
if (isDigitsOrSpecial(month)) {
System.out.print("proceed");
break;
} else if (isString(month)) {
System.out.print("proceed");
break;
}
} while (true);
// for the validation of current meter reading
do {
System.out.print("\nEnter current reading: ");
try {
current = scan.nextFloat();
System.out.println("proceed");
currents = String.format("%.2f", current);
if (current <= 0) {
System.out.println("Invalid input");
}
} catch (InputMismatchException a) {
System.out.println("Must enter a number");
scan.next();
}
} while (current <= 0);
// for the validation of recent meter reading
do {
System.out.print("Enter recent reading: ");
try {
recent = scan.nextFloat();
if (recent < current) {
System.out.println("proceed");
recents = String.format("%.2f", recent);
break;
} else {
System.out.println("recent must be less than current");
}
} catch (InputMismatchException a) {
System.out.println("Must enter a number");
scan.next();
}
} while (true);
difference = current - recent;
multiply = difference * 50;
System.out.println("====================================================================================");
System.out.println("MONTH " + " RECENT " + "CURRENT " + "TOTAL USAGE " + "Price per unit " + "TOTAL AMOUNT ");
System.out.println((s + (" ") + recents + (" kW") + (" ") + currents + (" kW") + (" ") + difference + (" ") + ("50php") + (" ") + multiply));
}
public static boolean isDigitsOrSpecial(String month) {
Scanner scan = new Scanner(System.in);
if (month != null) {
for (char ch : month.toCharArray()) {
if (Character.isLetter(ch)) {
return false;
}
}
}
int we = Integer.parseInt(month);
s = Integer.toString(we);
if (null == month) {
s = scan.nextLine();
} else switch (we) {
case 01:
s = "January";
break;
case 02:
s = "February";
break;
case 03:
s = "March";
break;
case 04:
s = "April";
break;
case 05:
s = "May";
break;
case 06:
s = "June";
break;
case 07:
s = "July";
break;
case 8:
s = "August";
break;
case 9:
s = "September";
break;
case 10:
s = "October";
break;
case 11:
s = "November";
break;
case 12:
s = "December";
break;
default:
System.out.println("You have entered an invalid number of month");
}
return true;
}
public static boolean isString(String month) {
Scanner scan = new Scanner(System.in);
if (null != month) {
char[] chars = month.toCharArray();
s = scan.nextLine();
for (char c : chars) {
if (!Character.isLetter(c)) {
return false;
}
}
}
if (!(month.length() >= 3)) {
System.out.println("Name of month must be at least 3 letters.Please try again");
return false;
} else if (month.startsWith("jan") || month.startsWith("JAN") || month.startsWith("Jan")) {
s = "January";
}
return true;
}
}
I see we have added additional scanner statements inside isDigit or isString methods. I have removed them and it looks good to me.
public static boolean isDigitsOrSpecial(String month) {
if (month != null) {
for (char ch : month.toCharArray()) {
if (Character.isLetter(ch)) {
return false;
}
}
}
int we = Integer.parseInt(month);
switch (we) {
case 01:
s = "January";
break;
case 02:
s = "February";
break;
case 03:
s = "March";
break;
case 04:
s = "April";
break;
case 05:
s = "May";
break;
case 06:
s = "June";
break;
case 07:
s = "July";
break;
case 8:
s = "August";
break;
case 9:
s = "September";
break;
case 10:
s = "October";
break;
case 11:
s = "November";
break;
case 12:
s = "December";
break;
default:
System.out.println("You have entered an invalid number of month");
return false;
}
return true;
}
public static boolean isString(String month)
{
if (null != month) {
char[] chars = month.toCharArray();
for (char c : chars) {
if (!Character.isLetter(c)) {
return false;
}
}
}
if (!(month.length() >= 3)) {
System.out.println("Name of month must be at least 3 letters.Please try again");
return false;
}
return true;
}

Problems calling my methods, can someone offer some input?

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

Calculate a day based on user input: always the same day being returned

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

Hex to decimal conversion from a bufferreader

I am having a lot of trouble getting my code to read a certain file, which has 4 hex codes, using buffer reader and converting it to decimal. I was able to get the bufferreader to read the text file and output it to the compiler but i need the program to store the 4 values and have my method convert hex to decimal. This is what i have so far:
import java.io.BufferedReader;
import static java.lang.System.*;
import java.io.*;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class HexToDecimal {
public static int hexToDecimal(String hexInput) throws IOException {
int decimal = 0;
int len = hexInput.length();
FileReader in = new FileReader("results.txt");
BufferedReader br = new BufferedReader(in);
String line;
while ((line = br.readLine()) != null) {
out.printf(line + "\n");
}
in.close();
for (int i = 0; i < len; ++i) {
char c = hexInput.charAt(i);
int cValue;
switch (c) {
case '1':
cValue = 1;
break;
case '2':
cValue = 2;
break;
case '3':
cValue = 3;
break;
case '4':
cValue = 4;
break;
case '5':
cValue = 5;
break;
case '6':
cValue = 6;
break;
case '7':
cValue = 7;
break;
case '8':
cValue = 8;
break;
case '9':
cValue = 9;
break;
case 'A':
cValue = 10;
break;
case 'B':
cValue = 11;
break;
case 'C':
cValue = 12;
break;
case 'D':
cValue = 13;
break;
case 'E':
cValue = 14;
break;
case 'F':
cValue = 15;
break;
default: // unexpected character
throw new IllegalArgumentException("Non-hex character " + c
+ " found at position " + i);
}
decimal = 16 * decimal + cValue;
}
return decimal;
}
public static void main(String[] args) {
}
}
Also i can't use parseInt that's why i'm using case breaks. Which is also giving me trouble when it comes to converting hex to decimal. Any help at all is greatly appreciated.
You could change your code in that way and it will work:
import static java.lang.System.out;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;
public class HexToDecimal {
public static BigInteger hexToDecimal(String hexInput) throws IOException {
BigInteger decimal = BigInteger.ZERO;
int len = hexInput.length();
for (int i = len - 1; i >= 0; i--) {
char c = hexInput.charAt(len - i - 1);
BigInteger cValue;
switch (c) {
case '1':
cValue = BigInteger.ONE;
break;
case '2':
cValue = BigInteger.valueOf(2l);
break;
case '3':
cValue = BigInteger.valueOf(3l);
break;
case '4':
cValue = BigInteger.valueOf(4l);
break;
case '5':
cValue = BigInteger.valueOf(5l);
break;
case '6':
cValue = BigInteger.valueOf(6l);
break;
case '7':
cValue = BigInteger.valueOf(7l);
break;
case '8':
cValue = BigInteger.valueOf(8l);
break;
case '9':
cValue = BigInteger.valueOf(9l);
break;
case 'A':
cValue = BigInteger.valueOf(10l);
break;
case 'B':
cValue = BigInteger.valueOf(11l);
break;
case 'C':
cValue = BigInteger.valueOf(12l);
break;
case 'D':
cValue = BigInteger.valueOf(13l);
break;
case 'E':
cValue = BigInteger.valueOf(14l);
break;
case 'F':
cValue = BigInteger.valueOf(15l);
break;
default: // unexpected character
throw new IllegalArgumentException("Non-hex character " + c
+ " found at position " + i);
}
decimal = decimal.add(cValue
.multiply(BigInteger.valueOf(16).pow(i)));
}
return decimal;
}
public static void main(String[] args) throws IOException {
FileReader in = new FileReader("results.txt");
BufferedReader br = new BufferedReader(in);
String line;
while ((line = br.readLine()) != null) {
String[] hexNums = line.split(" ");
for (String hex : hexNums)
out.printf(hexToDecimal(hex) + "\n");
}
in.close();
}
}
If you have to big numbers then you get a wrong answer with int as type so you have to use BigInteger and then the code looks like above with reading from file and printing to the output stream.
I hope it helps.
As Leonid Glanz said just convert the hex String to decimal with Integer.parseInt(hexString, 16). To store more than one value just use a ArrayList.
Edit: Sry didn't read your Op correctly
Here is a bit of code you can use:
import java.io.BufferedReader;
import static java.lang.System.*;
import java.io.*;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class HexToDecimal {
public static ArrayList<Integer> hexToDecimal() throws IOException {
FileReader in = new FileReader("results.txt");
BufferedReader br = new BufferedReader(in);
String line;
String ram = "";
ArrayList<String> lines = new ArrayList<>();
ArrayList<Integer> output = new ArrayList<>();
while ((line = br.readLine()) != null) {
lines.add(line);
}
for(String y : lines){
ram = "";
for(char x : y.toCharArray()){
ram += convert(x);
}
output.add(Integer.parseInt(ram));
}
in.close();
return output;
}
public static int convert(char x){
if(x == '1'){
return 1;
}else if(x == '2'){
return 2;
}else if(x == '3'){
return 3;
}else if(x == '4'){
return 4;
}else if(x == '5'){
return 5;
}else if(x == '6'){
return 6;
}else if(x == '7'){
return 7;
}else if(x == '8'){
return 8;
}else if(x == '9'){
return 9;
}else if(x == 'A'){
return 10;
}else if(x == 'B'){
return 11;
}else if(x == 'C'){
return 12;
}else if(x == 'D'){
return 13;
}else if(x == 'E'){
return 14;
}else if(x == 'F'){
return 15;
}else{
return 0;
}
}
public static void main(String[] args) {
try {
System.out.println(hexToDecimal());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

printing out the day of the week in Java

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..

Categories