My array looks something like this
String[] dayNames = new String[DAYS_IN_WEEK];
dayNames[0] = "Sunday";
dayNames[1] = "Monday";
dayNames[2] = "Tuesday";
dayNames[3] = "Wednesday";
dayNames[4] = "Thursday";
dayNames[5] = "Friday";
dayNames[6] = "Saturday";
I need to print the index of the array using a method findDay.
so if "Saturday" was selected, i would need 6 to be returned.
Thanks for your time =D
P.s. No answers please? Just suggestions =)
UPPDATE**
my array will not compile. This is exactly what i have:
private static final int DAYS_IN_WEEK = 7;
String[] dayNames;
dayNames = new String[DAYS_IN_WEEK]
// Declare an array of Strings named dayNames
dayNames[0] = "Sunday";
dayNames[1] = "Monday";
dayNames[2] = "Tuesday";
dayNames[3] = "Wednesday";
dayNames[4] = "Thursday";
dayNames[5] = "Friday";
dayNames[6] = "Saturday";
and I get multiple errors starting with:
Weekdays.java:12: error: <identifier> expected
dayNames = new String[DAYS_IN_WEEK]
I don't understand why. I literally copied the EXACT format from
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
You could do this...
int index = Arrays.asList(dayNames).indexOf("Saturday");
I'll leave printing the index value as an exercise for you.
Use a map your key is day and value is index.
Key => Sunday , Monday , Tuesday .....
Value = > 0,1,2 ..
Map the value against the key you required.
Well, one way to do it would be like this:
public int findDay(String dayString) {
if (dayString.equals("Sunday") {
return 0;
}
else if (dayString.equals("Monday") {
...
You get the gist of it - but that's a fairly crufty solution.
An alternative would be to use Java's enumerated values:
public enum Day {
SUNDAY(0), MONDAY(1), TUESDAY(2), WEDNESDAY(3) ...
private final int i;
private Day(int value) {
i = value;
}
public int getNumericRepresentation() {
return i;
}
}
Then you can actually have an array of enumerations, like:
Day[] days = new Day[Day.values().size()];
int i = 0;
for (Day day : Day.values()) {
days[i] = day;
i++;
}
And to print out a day's numeric representation you just use:
day.getNumericRepresentation();
Related
First and foremost : Homework
Second : We received 90% of this code pre-written from the teacher, we were asked to make some changes to the class itself (implement comparable) as well as doing some small changes(override toString method, create a quicksort method).
The part of the assignment that I am struggling with is the following :
Use loop and random number generator to create an array of 100 dates in the time
range from January 1 2018 to December 31 2018.
Use Quicksort generic method to sort the dates in the array
My code is below.
package date;
import java.util.Random;
public class DateQuicksort implements Comparable {
// variables
int days;
String months;
int years;
// Constructor without parameters
public DateQuicksort() {
this.months = "January";
this.days = 1;
this.years = 1000;
}
// Constructor with parameters
public DateQuicksort(int days, String months, int years) {
super();
this.days = days;
this.months = months;
this.years = years;
}
// compareTo method
#Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
DateQuicksort obj = (DateQuicksort) o;
// logic to compare two Date object
if (this.getYears() > obj.getYears()) {
return 1;
} else if (this.getYears() < obj.getYears()) {
return -1;
} else {
// when same year
if (this.getMonths() > obj.getMonths()) {
return 1;
} else if (this.getMonths() < obj.getMonths()) {
return -1;
} else {
// when same month
if (this.getDays() > obj.getDays()) {
return 1;
} else if (this.getDays() < obj.getDays()) {
return -1;
} else {
// when both date are same
return 0;
}
}
}
}
// Generic quick sort method
public static <T extends Comparable<T>> void qsort(T[] arr, int a, int b) {
if (a < b) {
// variables
int i = a, j = b;
T x = arr[(i + j) / 2];
do {
// compare dates
while (arr[i].compareTo(x) < 0)
i++;
while (x.compareTo(arr[j]) < 0)
j--;
if (i <= j) {
T tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
} while (i <= j);
// recursive call
qsort(arr, a, j);
qsort(arr, i, b);
}
}
// override tostring method to print dates
#Override
public String toString() {
return monthString(this.getMonths()) + " " + this.getDays() + ", " + this.getYears();
}
private static String monthString(int monthNumber) {
switch (monthNumber) {
case 1:
return "January";
case 2:
return "February";
case 3:
return "March";
case 4:
return "April";
case 5:
return "May";
case 6:
return "June";
case 7:
return "July";
case 8:
return "August";
case 9:
return "September";
case 10:
return "October";
case 11:
return "November";
case 12:
return "December";
default:
throw new IllegalArgumentException("Bad month number!");
}
}
public int getDays() {
return days;
}
public void setDays(int days) {
if ((days <= 0) || (days > 31)) {
throw new IllegalArgumentException("Bad day!");
} else
this.days = days;
}
public int getMonths() {
if (this.months.equals("January"))
return 1;
else if (this.months.equals("February"))
return 2;
else if (this.months.equalsIgnoreCase("March"))
return 3;
else if (this.months.equalsIgnoreCase("April"))
return 4;
else if (this.months.equalsIgnoreCase("May"))
return 5;
else if (this.months.equals("June"))
return 6;
else if (this.months.equalsIgnoreCase("July"))
return 7;
else if (this.months.equalsIgnoreCase("August"))
return 8;
else if (this.months.equalsIgnoreCase("September"))
return 9;
else if (this.months.equalsIgnoreCase("October"))
return 10;
else if (this.months.equals("November"))
return 11;
else if (this.months.equals("December"))
return 12;
else {
throw new IllegalArgumentException("Bad month!");
}
}
public void setMonths(String months) {
this.months = months;
}
public int getYears() {
return years;
}
public void setYears(int years) {
if ((this.years < 1000) || (this.years > 9999)) {
throw new IllegalArgumentException("Bad year!");
} else
this.years = years;
}
// main method
public static void main(String[] args) {
for(int count = 0; count < 100; count++) {
int aDay = 0;
Random DayGenerator = new Random();
for(int d=0; d<100; d++){
aDay = (DayGenerator.nextInt(31)+1);
}
int aMonth = 0;
Random MonthGenerator = new Random();
for(int m = 0; m < 100; m++) {
aMonth = (MonthGenerator.nextInt(12)+1);
DateQuicksort[] newDates = { new DateQuicksort(aDay, monthString(aMonth), 2018)};
// print date before sort
System.out.println("Dates before sort :\n");
for (DateQuicksort date : newDates) {
// print
System.out.println(date.toString());
}
// call sort method
DateQuicksort.<DateQuicksort>qsort(newDates, 0, newDates.length - 1);
// after sort
System.out.println("\nDates After sort :\n");
for (DateQuicksort date : newDates) {
// print
System.out.println(date.toString());
}
}
}
}
}
It's been a long day, and I am sure there is something really stupid that I am missing or overlooking to get this to do what I want. Right now it's creating a new array and that is caused by the for loop I created.
Currently my head is gravitating towards making new methods for generating a random day and a random month and then calling those methods in a forloop to insert into the array. Granted, I am much better at walking through these ideas in words, then I am with code.
If you look at the various functions of Java Date, you find several function setting a value (setYear etc), such as described here:
https://docs.oracle.com/javase/8/docs/api/java/util/Date.html
For all your 100 random values, I would generate a random number in a given range (i.e. for months, a random number from 1 to 12) and set it correspondingly. So, per one date you would call three times a random number generator.
(Too make it simple, you could either limit it to 1..28 for days, or you need a table or an algorithm determining whether 29,30,31 is valid for that month in that year).
Alternatively, use setTime with a random millisec value; which should be in the range you want (calculate millisec for your start date, add a random with a maximum value for your intended time frame)
Basically, I have a variable 'prime'. It can only take values between 0 and 6. Based on its value, I want a string 'result' to be Sunday if prime is 0, Monday if 1, etc. Currently, it's coded this way:
String result = new String();
if (prime == 0)
{
result = "Sunday";
}
if (prime == 1)
{
result = "Monday";
}
if (prime == 2)
{
result = "Tuesday";
}
if (prime == 3)
{
result = "Wednesday";
}
if (prime == 4)
{
result = "Thursday";
}
if (prime == 5)
{
result = "Friday";
}
if (prime == 6)
{
result = "Saturday";
}
else
{
result = "Check your code.";
}
I'm wondering if there's a faster way to do this? I've created an array with the days of the week:
String[] days = new String[7];
days [0] = "Sunday";
days [1] = "Monday";
days [2] = "Tuesday";
days [3] = "Wednesday";
days [4] = "Thursday";
days [5] = "Friday";
days [6] = "Saturday";
How do I quickly and elegantly code it so that if the value of prime is 0, the string 'result' is the first element of the array, and so on until if prime is 6, the string 'result' is the seventh element?
You already have all the valid values stored in a simple lookup table, you just need to ensure that the requested value is within the range of available values.
The basic answer would be to do something like...
if (prime >= 0 && prime < days.length) {
result = days[prime];
} else {
result = prime + " is not within a valid range";
// Or throw an exception
}
What this does is makes sure that the prime value is within the valid range of acceptable values (0..days.length - 1), other wise it returns an error message (or you could throw an exception).
Remember, arrays are 0 indexed, hence the need to use < days.length (less then) and not <= days.length (less then or equals to)
You were close. For those saying Switch or if chains, it's overkill for this problem.
result = days[Math.abs(prime % days.length)];
The array acts like a switch statement, and the modulus operator wrapped in the Math.abs (absolute value) acts like a safety net to stay with in the valid range of the array 0-6.
Credits to #MadProgrammer for the Math.abs
From Tutorials Point
Modulus - Divides left hand operand by right hand operand and returns remainder
Why don't you use the DayOfWeek class?
import java.time.DayOfWeek;
and try this...
try {
DayOfWeek dayOfWeek = DayOfWeek.of(++prime);
System.out.println(dayOfWeek.getDisplayName(TextStyle.FULL, Locale.getDefault()));
} catch (java.time.DateTimeException ex) {
System.out.println("Invalid value for DayOfWeek");
}
Note that we have to do ++prime since your code starts in zero and the enum in one.
If you have to set Sunday as the first day (instead of Monday that is the first in the enum)... the minus method will do the trick:
DayOfWeek dayOfWeek = DayOfWeek.of(++prime).minus(1);
EDIT: advantages and disadvantages of the solution
Pros:
Don't require an object to maintain your days.
Don't use a conditional statement.
The text style and language can easily be changed.
Cons:
java 1.8 is required
You could simply do:
if (prime >= 0 && prime < days.length) result = days[prime];
else result = "Check your code."
Because prime is essentially the index of the day that you want.
You can use Enum and define yourself
public enum Week {
SUNDAY(1, "Sunday"), Monday(2, "Monday"), TUESDAY(3, "Tuesday"), WEDNESDAY(
4, "Wednesday"), THURSDAY(6, "Thursday"), FRIDAY(6, "Friday"), SATURDAY(
7, "Saturday");
private int id;
private String name;
static Map<Integer, String> map = new HashMap<Integer, String>();
static {
for (Week w : Week.values()) {
map.put(w.getId(), w.name);
}
}
private Week(int id, String name) {
this.setId(id);
this.setName(name);
}
public static String getNameById(int id) {
return map.get(id);
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
When I try to run this program, the result is always null, 0 0. Why do the values of monthName, day, and year not show up when the getDay() method is invoked and printed on the screen.
public class Assignment1 {
public static void main(String[] args) {
//creates an array of type Date filled with two LongDate objects
Date [] collectionOfDates = { new LongDate("February",2,1996), new LongDate("February",13,1999) };
// loops through the array and displays output of getDate() for each object
for( int i = 0; i < collectionOfDates.length; i++ ) {
System.out.println( collectionOfDates[i].getDate() );
}
}
}
For your information, the LongDate class is a subclass of the Date class which contains methods editDay() and editYear() along with several others. The LongDate method is listed below.
Any help greatly appreciated, Thanks. Also, feel free to comment if you want more information.
public class LongDate extends Date {
private String monthName;
private int day;
private int year;
public LongDate() {
}
public LongDate(String m, int d, int y) {
super.editday(d);
super.edityear(y);
editMonth(m);
}
public void setDate(String m, int d, int y) {
monthName = m;
day = d;
year = y;
}
public String getDate() {
StringBuilder fullDate = new StringBuilder();
fullDate.append(monthName);
fullDate.append(" ");
fullDate.append(day);
fullDate.append(", ");
fullDate.append(year);
return fullDate.toString();
}
public String getShortDate() {
int month = 0;
if (monthName == "January") {
month = 1;
} else if (monthName == "February") {
month = 2;
} else if (monthName == "March") {
month = 3;
} else if (monthName == "April") {
month = 4;
} else if (monthName == "May") {
month = 5;
} else if (monthName == "June") {
month = 6;
} else if (monthName == "July") {
month = 7;
} else if (monthName == "August") {
month = 8;
} else if (monthName == "September") {
month = 9;
} else if (monthName == "October") {
month = 10;
} else if (monthName == "November") {
month = 11;
} else if (monthName == "December") {
month = 12;
}
StringBuilder shortDate = new StringBuilder();
shortDate.append(month);
shortDate.append("/");
shortDate.append(day);
shortDate.append("/");
shortDate.append(year);
return shortDate.toString();
}
protected String editMonth(String m) {
// asks person to try again if month is not capitalized and spelled properly
if (m != "January" && m != "February" && m != "March" && m != "April" && m != "May" && m != "June" && m != "July" && m != "August" && m != "September" && m != "October" && m != "November" && m != "December") {
m = Input.getString( "Invalid month. Please type the month again." );
return m;
} else
return m;
}
}
There's nothing in the constructor of LongDate which sets the fields (monthName, day, and year) that getDate() reads.
I assume that the Date#editDay() and Date#editYear() functions look similar to LongDate#editMonth(). Note that editMonth() does not assign a value to the monthName field!
You should compare your strings with equals() and not ==. The equals() method compares string values, whereas == compares object references, which is not what you want here. So change:
if (monthName == "January") {
to:
if (monthName.equals("January")) {
and similarly for the other comparisons.
Couple of issues. First:
public LongDate(String m, int d, int y) {
super.day(d);
super.year(y);
editMonth(m);
}
You don't show Date so it is unclear to us what day() and year() are supposed to do, but regardless:
public class LongDate extends Date {
private String monthName;
private int day;
private int year;
...
}
Your declarations of these fields are hiding any similar fields that the base presumably has. In any case, at no point in your constructor are you setting this.day or this.year to anything, and so, of course, they remain at their initial value of 0.
You need to clean up your code a bit. Either refer to the correct day and year, or make sure you are setting and getting the base class' version of those fields instead of redeclaring them in the subclass (again, not sure what your base implementation does).
You may want to have a look at the official tutorial on Inheritance. It's concise and well-written and covers topics like overriding methods, hiding fields, etc. I think it will give you a good starting point for solving your issues here.
And, of course, comparing strings with == here will lead to other issues in the future: How do I compare strings in Java?
Your editMonth method returns a string, instead it should set the month:
monthName = m;
Another option is to keep the editMonth method the same, but in your constructor put:
monthName = editName(m);
I've actually been browsing for quite a while on this site, sadly without much progress. Thanks to a lot of extremely useful answers, I've learned quite a bunch of stuff though!
I'm learning Java since ... about 4 days (I guess?) so I'm not very experienced in the methods I can use.
There's this assignment we got at our univ. We shall write a program that returns how many days have passed between two dates. The only restriction is to keep the program as simple as possible, we're not allowed to use "complicated methods".
Sadly, my program is kind of stuck. If I try it out e.g. the dates 23 01 1994 and 07 04 1997, it counts only up to 01 01 1997 and suddenly stops. I have no idea why that happens, I even doubt if I fully understood what I wrote there.
Anyways, here's my code:
import java.util.Arrays;
import java.util.Scanner;
public class Datecalc {
public static int yearcounter,monthcounter,daycounter,days;
public static int[] input() {
Scanner input = new Scanner(System.in);
//Eingabe der Daten
String day1 = input.next();
String month1 = input.next();
String year1 = input.next();
String day2 = input.next();
String month2 = input.next();
String year2 = input.next();
int day1int = Integer.parseInt(day1);
int month1int = Integer.parseInt(month1);
int year1int = Integer.parseInt(year1);
int day2int = Integer.parseInt(day2);
int month2int = Integer.parseInt(month2);
int year2int = Integer.parseInt(year2);
int [] eingabe = new int [6];
eingabe[0] = day1int;
eingabe[1] = month1int;
eingabe[2] = year1int;
eingabe[3] = day2int;
eingabe[4] = month2int;
eingabe[5] = year2int;
return eingabe;
// put everything into an array to be able to use it in the main method
}
public static void main(String[] args) {
int[] eingabe = input();
days=0;
daycounter = eingabe[0];
monthcounter = eingabe[1];
yearcounter = eingabe[2];
Integer[] einunddreissig = {1,3,5,7,8,10,12}; //months with 31 days
Integer[] dreissig = {4,6,9,11}; // months with 30 days
while (daycounter != eingabe[3] && monthcounter != eingabe[4] && yearcounter != eingabe[5] ) {
// if its a month that has 31 days
if ( Arrays.asList(einunddreissig).contains(monthcounter) ) {
for (int i = daycounter; i <= 31; i++) {
days++;
}
daycounter=1;
monthcounter++;
}
// if its a month with 30 days
if ( Arrays.asList(dreissig).contains(monthcounter) ) {
for (int i = daycounter; i <= 30; i++) {
days++;
daycounter++;
}
daycounter=1;
monthcounter++;
// february
} else if ( monthcounter == 2) {
for (int i = daycounter; i <= 28; i++) {
days++;
}
daycounter=1;
monthcounter++;
} else if (monthcounter==13) {
monthcounter=1;
yearcounter++;
}
}
// checking how many days were counted and comparing the input (eingabe[something]) to how far the daycounter reached
System.out.println(" "+days);
System.out.println(" "+daycounter+" "+monthcounter+" "+yearcounter);
System.out.println(eingabe[3]+" "+eingabe[4]+" "+eingabe[5]);
}
}
I hope there is somebody who might be so kind to give me a hint how to fix that.
I would separate this out into two different functions, one that counts the days until the end of the current year and another which counts the days since the beginning of the current year. Then you can put the total days in terms of those values.
First write a generic sum() function:
public static int sum(int[] a, int start, int end){
int sum = 0;
for(int i = start; i < end; i++) sum += a[i];
return sum;
}
Then use the sum() function to easily compute daysToEnd and daysFromStart:
static int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
public static int daysToEnd(int day, int month){
return sum(daysInMonth, month - 1, 12) - day;
}
public static int daysFromStart(int day, int month){
return sum(daysInMonth, 0, month - 1) + day;
}
public static void main(String... args){
int[] date1 = {23, 1, 1994};
int[] date2 = {1, 1, 1997};
// This actually works for same or different years
int days = daysToEnd(date1[0], date1[1]) +
365*(date2[2] - date1[2] - 1) +
daysFromStart(date2[0], date2[1]);
System.out.println(days);
}
Do you have to use loops? Here's some food for thought -- imagine this as a simple algebra problem. In your program, each date is modeled as a collection of quantities, each of a different unit. Once you obtain uniform units, you can just do the arithmetic.
In the UNIX world we use an agreed-upon reference date called the "epoch", 12:00 AM on 01 January, 1970 as a reference date. Kind of like "tare" on a balance. All other dates can be represented as some number of seconds relative to that time.
I would construct the passed in user input to java.util.Date type. But I am assuming line by line input. You can construct a string using StringBuilder if you want to get day,mth,year separately.
try{
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
DateFormat df = new SimpleDateFormat ("dd/MM/yyyy");
System.out.println("Enter Date1");
String dateSt1= br.readLine(); // Accepts date1 as string
System.out.println("Enter Date2");
String dateSt2= br.readLine(); // Accepts date2 as string
Date date1=df.parse(dateSt1); // Date String to Date
Date date2=df.parse(dateSt2);
}catch(IOException ex)
}catch(ParseExceptionOfSomesort pex)
}
then use this to get the difference in days -
int diffInDays = (int)( (date2.getTime() - date1.getTime())
/ (1000 * 60 * 60 * 24) )
If you get this in negative, that means the second date is before first date.
Think: Do I have to do it using a loop or hasn't java already added some utility method to do date compare?
What makes something "complicated" though? Writing too many lines of code or using existing java library?
So I'm writing a method called getThanksgiving. It works as is and it's part of a much larger class but I needed advice on how to make it more efficient. The getWeekDay method just returns what day of the week November 1 is on a user-inputted year.
public String getThanksgiving(){
String a = getWeekDay(11, 1);
int offset = 0;
if(a.equals("Friday")){
offset = 7;
}
if(a.equals("Saturday")){
offset = 6;
}
if(a.equals("Sunday")){
offset = 5;
}
if(a.equals("Monday")){
offset = 4;
}
if(a.equals("Tuesday")){
offset = 3;
}
if(a.equals("Wednesday")){
offset = 2;
}
if(a.equals("Thursday")){
offset = 1;
}
int date = 21 + offset;
thanksgiving = "Thursday, November " + date;
return thanksgiving;
}
I tried rewriting it as a for loop but it's not working.
public String getThanksgiving(){
String a = getWeekDay(11, 1);
int offset = 8;
String[] wTable = {"Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"};
for(int i = 1; i < 8; i++){
if(a.equals(wTable[i - 1])){
offset --;
}
}
}
Also, the idea of offset and adding 21 is just something my teacher wants us to do. Thanks in advance!
you can use switch case
like
switch(a )
{
case "Monday":
offset = 4;
break;
case "Tuesday":
offset = 3;
break;
}
reference
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
I don't think you can make it "more efficient" (i.e. runtime performance). If you want to make your code more readable shorter, I think you're almost there
String[] wTable = {null, "Thursday", "Wednesday", "Tuesday", "Monday", "Sunday", "Saturday", "Friday"};
for(int i = 1, n = wTable.lenght; i < n; i++) {
if(a.equals(wTable[i])){
offset = i;
break;
}
}
To specifically address your question on 'how to make this method more efficient', one thing to note is that the method evaluates every if statement even in the case when you already found your solution. Using 'bare bones' java if's you could add a condition to check when the day has been found in this way:
int offset = 0;
boolean found = false;
if(!found && a.equals("Friday")){
offset = 7;
found = true;
}
if(!found && a.equals("Saturday")){
offset = 6;
found = true;
}
This flag will marginally reduce runtime by virtue of shortcut evaluation of the && (and) operator, only executing the string comparison until a match is found. You can achieve a similar performance result with a for and using break to get out of the loop when you have found a matching element.
A better alternative would be using a Map data structure:
Map<String, Integer> daysByOffset = new HashMap<String,Integer>();
// this 'setup' part you only do once
daysByOffset.put("Friday", 7);
daysByOffset.put("Saturday", 6);
...
Then the lookup part is very efficient, as the lookup in a hashmap is O(1):
int offset = daysByOffset.get(day);
An elegant alternative would be using enums that encapsulate the offset information:
public enum DaysWithOffset {
FRIDAY(7), SATURDAY(6),..., THURSDAY(1);
private final offset;
private DaysWithOffset(int offset) {
this.offset = offset;
}
public int getOffset() {
return offset;
}
}
After the enum is defined, each enum constant will contain the corresponding offset info:
FRIDAY.getOffset() // = 7
You can calculate the offset by resolving the enum from the provided String and asking the offset value from it:
...
String a = getWeekDay(11, 1);
int offset = DaysWithOffset.valueOf(day.toUpperCase()).getOffset();
...
Coming back to the question on which option is more efficient, both map and enum have an O(1) lookup, (the Enum lookup being slightly better by the optimized internal enum dictionary. Yet, the enum operation requires a toUpperCase(), while the map doesn't) both these options will perform a lot better than a list of if's (the original version) or a for loop.
I include these options for completeness of the answer and also for you to have a 'sneak preview' of the possibilities that the Java language offers.
Now a teaser: If you were doing this in Scala, you'd write something like this:
val daysByOffset = Map("Friday" -> 7, "Saturday" -> 6,...,"Thursday" ->1)
def thanksGiving(day:String):String = "Thursday, November " + (daysByOffset(day)+21)
If I were learning a language today, it would be Scala.
how about this?
private final static Map<String, int> dayMap = new HashMap<String,int>()
{
dayMap.put("Monday", 0);
// do for the rest
};
in your method:
public String getThanksgiving(){
String a = getWeekDay(11, 1);
//do a lookup
int result = dayMap.get(a);
// do somthing with it. and return
return "blah "+ result;
}