patternjavaMinor
Computing the name of the month
Viewed 0 times
thenamemonthcomputing
Problem
I created the following program that transforms a numerical month into the corresponding textual month. I initially calculated the
starPoint and endPoint in the class constructor; then I changed that calculation to the getName method. Which is a better option? Calculating in the class constructor, or in a separate method like shown in the code?/**
* Created by Robert Holland on 25/11/2016.
*
* A class that accepts a number and calculates
* the corresponding month. Once the month has
* been calculated it will then be returned.
*
*/
public class Month
{
public static final String MONTHS = "January " + "February " + "March " +
"April " + "May " + "June " +
"July " + "August " + "September " +
"October " + "November " + "December ";
private int monthNumber;
//Construct a month class that has a value equal to the numerical month
//@param uMonthNumber the number of the month to find the correspondance.
public Month(int uMonthNumber)
{
monthNumber = uMonthNumber;
}
//Determine the name that corresponds to the month number.
//@return month the name of the corresponding month.
public String getName()
{
String month;
int startPoint;
int endPoint;
endPoint = monthNumber * 10;
startPoint = endPoint - 10;
month = MONTHS.substring(startPoint, endPoint);
return month;
}
}Solution
This exists already:
It's not the prettiest to use but it's there.
Don't re-write code that's in your standard libraries :)
It's not the prettiest to use but it's there.
import java.time.*;
import java.time.format.*;
import java.util.*;
public class Example {
public static void main(String[] args) {
Month month = Month.of(2);
System.out.printf("%s", month.getDisplayName(TextStyle.FULL, new Locale("en")));
// outputs:
// February
}
}Don't re-write code that's in your standard libraries :)
Code Snippets
import java.time.*;
import java.time.format.*;
import java.util.*;
public class Example {
public static void main(String[] args) {
Month month = Month.of(2);
System.out.printf("%s", month.getDisplayName(TextStyle.FULL, new Locale("en")));
// outputs:
// February
}
}Context
StackExchange Code Review Q#148112, answer score: 3
Revisions (0)
No revisions yet.