Java - Guava Table Not Returning Value - java

I am using Google's Guava library for the Table class.
I have the table define like this:
private Table<ThreePartKey, DateTime, UnitDay> table = TreeBasedTable.create();
ThreePartKey is an object that contains 3 string values as fields. It is being used as the Row index in the table. DateTime is a Joda Time object being used as the Column index of the table. UnitDay is a plain old java object that is the Value of the table.
I have populated the table, and later in my code I want to access a specific cell of the table. I use the following code:
UnitDay tempUnitDay = table.get(threePartKey, dateTime);
But tempUnitDay is null. I've run this in Eclipse debug mode, and neither threePartKey nor dateTime is null. There should not be a null value in the table.
Does anyone have any idea what I am doing wrong?
EDIT:
#TR1 I thought of that, but it should have a value for that column/row. I created a list of ThreePartKeys and a list of DateTimes, then created a table from those lists with an empty UnitDay as the value. Then I go back an iterate through the same values again to populate the UnitDay values.
Here is the code for my ThreePartKey class:
public class ThreePartKey implements Comparable<ThreePartKey> {
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((facilityCode == null) ? 0 : facilityCode.hashCode());
result = prime
* result
+ ((facilityGroupCode == null) ? 0 : facilityGroupCode
.hashCode());
result = prime * result
+ ((unitCode == null) ? 0 : unitCode.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ThreePartKey other = (ThreePartKey) obj;
if (facilityCode == null) {
if (other.facilityCode != null)
return false;
} else if (!facilityCode.equals(other.facilityCode))
return false;
if (facilityGroupCode == null) {
if (other.facilityGroupCode != null)
return false;
} else if (!facilityGroupCode.equals(other.facilityGroupCode))
return false;
if (unitCode == null) {
if (other.unitCode != null)
return false;
} else if (!unitCode.equals(other.unitCode))
return false;
return true;
}
private String facilityGroupCode;
private String facilityCode;
private String unitCode;
public void setFacilityGroupCode (String facilityGroupCode) {
this.facilityGroupCode = facilityGroupCode;
}
public void setFacilityCode (String facilityCode) {
this.facilityCode = facilityCode;
}
public void setUnitCode (String unitCode) {
this.unitCode = unitCode;
}
public String getFacilityGroupCode () {
return facilityGroupCode;
}
public String getFacilityCode () {
return facilityCode;
}
public String getUnitCode () {
return unitCode;
}
#Override
public int compareTo(ThreePartKey o) {
return (100*(unitCode.compareTo(o.unitCode))) +
(10*(facilityCode.compareTo(o.unitCode))) +
(facilityGroupCode.compareTo(o.facilityGroupCode));
}
}
And here is my code that creates the table:
public void setUpTable () {
for (DateTime day : uniqueDays) {
for (ThreePartKey unit : trueUniqueUnits) {
UnitDay unitDay = new UnitDay();
String unitCode = unit.getUnitCode();
unitDay.setDay(day);
unitDay.setUnitCode(unit.getUnitCode());
unitDay.setFacilityCode(unit.getFacilityCode());
unitDay.setFacilityGroupCode(unit.getFacilityGroupCode());
table.put(unit, day, unitDay);
}
}
}
public void populateTable () { //FIX THIS TO INCLUDE ThreePartKey
for (CensusHour hour : allHours) {
DateTime minHour = hour.getDateTaken().withTimeAtStartOfDay();
DateTime day = hour.getDateTaken().withTimeAtStartOfDay();
String unit = hour.getUnitCode();
ThreePartKey key = new ThreePartKey();
key.setFacilityCode(hour.getFacilityCode());
key.setFacilityGroupCode(hour.getFacilityGroupCode());
key.setUnitCode(hour.getUnitCode());
UnitDay tempUnitDay = table.get(key, day);
tempUnitDay.setFacilityId(hour.getFacilityId());
tempUnitDay.setFacilityName(hour.getFacilityName());
tempUnitDay.setUnitId(hour.getUnitId());
tempUnitDay.setUnitName(hour.getUnitName());
tempUnitDay.setPortalCensusFileId(hour.getPortalCensusFileId());
tempUnitDay.setDay(minHour);
tempUnitDay.setFacilityCode(hour.getFacilityCode());
tempUnitDay.setFacilityGroupCode(hour.getFacilityGroupCode());
tempUnitDay.setFacilityGroupName(hour.getFacilityGroupName());
int objectHour = hour.getHourOfDay();
double occupancy = hour.getOccupancy();
switch (objectHour) {
case 0: tempUnitDay.setCensusHour0(occupancy);
break;
case 1: tempUnitDay.setCensusHour1(occupancy);
break;
case 2: tempUnitDay.setCensusHour2(occupancy);
break;
case 3: tempUnitDay.setCensusHour3(occupancy);
break;
case 4: tempUnitDay.setCensusHour4(occupancy);
break;
case 5: tempUnitDay.setCensusHour5(occupancy);
break;
case 6: tempUnitDay.setCensusHour6(occupancy);
break;
case 7: tempUnitDay.setCensusHour7(occupancy);
break;
case 8: tempUnitDay.setCensusHour8(occupancy);
break;
case 9: tempUnitDay.setCensusHour9(occupancy);
break;
case 10: tempUnitDay.setCensusHour10(occupancy);
break;
case 11: tempUnitDay.setCensusHour11(occupancy);
break;
case 12: tempUnitDay.setCensusHour12(occupancy);
break;
case 13: tempUnitDay.setCensusHour13(occupancy);
break;
case 14: tempUnitDay.setCensusHour14(occupancy);
break;
case 15: tempUnitDay.setCensusHour15(occupancy);
break;
case 16: tempUnitDay.setCensusHour16(occupancy);
break;
case 17: tempUnitDay.setCensusHour17(occupancy);
break;
case 18: tempUnitDay.setCensusHour18(occupancy);
break;
case 19: tempUnitDay.setCensusHour19(occupancy);
break;
case 20: tempUnitDay.setCensusHour20(occupancy);
break;
case 21: tempUnitDay.setCensusHour21(occupancy);
break;
case 22: tempUnitDay.setCensusHour22(occupancy);
break;
case 23: tempUnitDay.setCensusHour23(occupancy);
break;
}
table.put(key, day, tempUnitDay);
}
}

Related

Missing return statement inside switch

i have a method which returns a boolean value . Ive added return statement in every case of my switch statements and added default which also returns a value but still im getting the "Missing return statement" .
Whats missing ?
private boolean isDateValid ()
{
if ((_day>31) || (_day<=0))
{
return true;
}
if ((_month>12) || (_month<=0))
{
return true;
}
if ((_year>9999) || (_year<1000))
{
return true;
}
switch (_month)
{
case 1:
if (_day>JANUARY)
return true;
break;
case 2:
if ((_year % 400 == 0) || ((_year % 4 == 0) && (_year % 100 != 0)))
{
if (_day>FEBRUARY_LEAP)
return true;
}
else if (_day>FEBRUARY)
return true;
break;
case 3:
if (_day>MARCH)
return true;
break;
case 4:
if (_day>APRIL)
return true;
break;
case 5:
if (_day>MAY)
return true;
break;
case 6:
if (_day>JUNE)
return true;
break;
case 7:
if (_day>JULY)
return true;
break;
case 8:
if (_day>AUGUST)
return true;
break;
case 9:
if (_day>SEPTEMBER)
return true;
break;
case 10:
if (_day>OCTOBER)
return true;
break;
case 11:
if (_day>NOVEMBER)
return true;
break;
case 12:
if (_day>DECEMBER)
return true;
break;
default: return false;
}
}
Consider this case :
case 3:
if (_day>MARCH)
return true;
break;
You only return a value if the condition is true.
Instead, write
case 3:
return _day>MARCH;
This will return true if the condition is met and false otherwise.
The same applies to all you case clauses.
because you are using if in your case statement( if that if expression doesn't match method will not have any return value )
case 3:
if (_day>MARCH)
return true;
break;
Add `return false;` above the last bracket `}` and replace each `break;` statement
private boolean isDateValid ()
{
if ((_day>31) || (_day<=0))
{
return true;
}
if ((_month>12) || (_month<=0))
{
return true;
}
if ((_year>9999) || (_year<1000))
{
return true;
}
switch (_month)
{
case 1:
if (_day>JANUARY)
return true;
return false;
case 2:
if ((_year % 400 == 0) || ((_year % 4 == 0) && (_year % 100 != 0)))
{
if (_day>FEBRUARY_LEAP)
return true;
}
else if (_day>FEBRUARY)
return true;
return false;
case 3:
if (_day>MARCH)
return true;
return false;
case 4:
if (_day>APRIL)
return true;
return false;
case 5:
if (_day>MAY)
return true;
return false;
case 6:
if (_day>JUNE)
return true;
return false;
case 7:
if (_day>JULY)
return true;
return false;
case 8:
if (_day>AUGUST)
return true;
return false;
case 9:
if (_day>SEPTEMBER)
return true;
return false;
case 10:
if (_day>OCTOBER)
return true;
return false;
case 11:
if (_day>NOVEMBER)
return true;
return false;
case 12:
if (_day>DECEMBER)
return true;
return false;
default: return false;
}
return false;
}
private boolean isDateValid ()
{
boolean flag = false;
if ((_day>31) || (_day12) || (_month9999) || (_yearJANUARY)
flag = true;
break;
case 2:
if ((_year % 400 == 0) || ((_year % 4 == 0) && (_year % 100 != 0)))
{
if (_day>FEBRUARY_LEAP)
flag = true;
}
else if (_day>FEBRUARY)
flag = true;
break;
case 3:
if (_day>MARCH)
flag = true;
break;
case 4:
if (_day>APRIL)
flag = true;
break;
case 5:
if (_day>MAY)
flag = true;
break;
case 6:
if (_day>JUNE)
flag = true;
break;
case 7:
if (_day>JULY)
flag = true;
break;
case 8:
if (_day>AUGUST)
flag = true;
break;
case 9:
if (_day>SEPTEMBER)
flag = true;
break;
case 10:
if (_day>OCTOBER)
flag = true;
break;
case 11:
if (_day>NOVEMBER)
flag = true;
break;
case 12:
if (_day>DECEMBER)
flag = true;
break;
default: return flag;
}
return flag;
}

How do I set variable to int and String?

I am making a card class, and need to set the face (The number on the card) to the numbers 1-13. However, on a card, a 1 is an ace, a 13 is a king, a 12 is a Queen, and an 11 is a jack. How do I also set the number 1, and 11-13 to a string such as ace, king, queen, or jack? Any help is appreciated!
public void setFace(int f)
{
if(f >= 1 && f <= 13)
face = f;
else
face = 1;
}
public int getFace()
{
return face;
}
I'm assuming you have field like
public int face;
I guess it will work if it's what you meant
public String getFace() {
switch (this.face) {
case 1:
face = "Ace";
break;
case 11:
face = "Jack";
break;
case 12:
face = "Queen";
break;
case 13:
face = "King";
break;
default:
return Integer.toString(face);
break;
}
}
What do you think about this code..?
public void setFace(int f) {
switch (f) {
case 1:
face = 1;
break;
case 11:
face = 1;
break;
case 12:
face = 1;
break;
case 13:
face = 1;
break;
default:
face = f;
break;
}
}
How about using enums?
public enum CardValue {
ACE(1), TWO(2), THREE(3), ..... KING(13);
private int value;
private CardValue(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public CardValue getValueFor(int x) {
// iterate through CardValue enum and return correct instance of the enum
}
}

How to make a sleep thread in For loop?

I'm working on a card game app and i finished the basic stuff and now i'm trying to make it look professional.
the first thing I want to do is the effect of the distribution of cards,
i want to make a shuffle card effect.
when a card is given to a player, I want at least 500 milliseconds difference to the next card that will be distributed to him.
ideas?
this is a part from my code..
private void SetTheGame() {
SetShuffleSound();
for ( int i = 0; i < Imagename.length;i++) {
Imagename[i] = (ImageView) findViewById(WTF[i]);
CountCards();
Random = getRandom();
SwitchImages SwitchMe = new SwitchImages(myNewArray[Random]);
int first = SwitchMe.ChangeImages();
Imagename[i].setImageResource(myNewArray[Random]);
Imagename[i].setVisibility(View.VISIBLE);
CardsCount valueOfCard = new CardsCount(myNewArray[Random]);
int a = valueOfCard.WhatsMyValue();
String b = valueOfCard.TheFamily();
switch (i) {
case 0:
if (first != 0) {
Imagename[0].setImageResource(first);
}
FirstColumnComputer.add(a);
FirstColumnComputerFAMILY.add(b);
break;
case 1:
if (first != 0) {
Imagename[1].setImageResource(first);
}
SecondColumnComputer.add(a);
SecondColumnComputerFAMILY.add(b);
break;
case 2:
if (first != 0) {
Imagename[2].setImageResource(first);
}
ThirdColumnComputer.add(a);
ThirdColumnComputerFAMILY.add(b);
break;
case 3:
if (first != 0) {
Imagename[3].setImageResource(first);
}
FourColumnComputer.add(a);
FourColumnComputerFAMILY.add(b);
break;
case 4:
if (first != 0) {
Imagename[4].setImageResource(first);
}
FifthColumnComputer.add(a);
FifthColumnComputerFAMILY.add(b);
break;
case 5:
FirstColumnPlayer.add(a);
FirstColumnPlayerFAMILY.add(b);
break;
case 6:
SecondColumnPlayer.add(a);
SecondColumnPlayerFAMILY.add(b);
break;
case 7:
ThirdColumnPlayer.add(a);
ThirdColumnPlayerFAMILY.add(b);
break;
case 8:
FourColumnPlayer.add(a);
FourColumnPlayerFAMILY.add(b);
break;
case 9:
FifthColumnPlayer.add(a);
FifthColumnPlayerFAMILY.add(b);
break;
}
Cards.remove(Random);
// MakeTheCardPause();
}
SentTheLinkedList();
}
MakeTheCardPause() is the problem...
private void MakeTheCardPause() {
Thread Timer = new Thread()
{
public void run()
{
try{
sleep(1000);
}catch(InterruptedException e)
{
e.printStackTrace();
}finally
{
//do something...
}
}
};
Timer.start();
}
thanks!
Many ways you can do this. Thread.sleep(500) is the way was you suggested but it is not what I would recommend. Here are two alternatives
Message Handler
An example
Handler mHandler = new Handler(){
public void handleMessage(Message msg){
super.handleMessage(msg);
switch(msg.what){
case shuffle:
// Do something
break;
case doneShuffle:
//Do something
}
}
};
Asynch Tasks
Here is an example:
private class shuffleCards extends AsyncTask<Card, Integer, Long> {
protected Long doInBackground(Card card) {
//Do something
//shuffle deck
// Escape early if cancel() is called
if (isCancelled()) break;
}
return deck;
}
protected void onProgressUpdate(Integer... progress) {
//Number of shuffled cards??
}
protected void onPostExecute(Long result) {
//Show card
}
}
Remember this is just a background task to display results. Your main thread will be handling the actual card values and handing them over to the Asynch task.
Good Luck
What about this? You need to have the sleep in the working thread, your code above is creating a new thread and telling it to sleep, which has no noticeable effect to the user.
private void SetTheGame() {
SetShuffleSound();
for ( int i = 0; i < Imagename.length;i++) {
Imagename[i] = (ImageView) findViewById(WTF[i]);
CountCards();
Random = getRandom();
SwitchImages SwitchMe = new SwitchImages(myNewArray[Random]);
int first = SwitchMe.ChangeImages();
Imagename[i].setImageResource(myNewArray[Random]);
Imagename[i].setVisibility(View.VISIBLE);
CardsCount valueOfCard = new CardsCount(myNewArray[Random]);
int a = valueOfCard.WhatsMyValue();
String b = valueOfCard.TheFamily();
switch (i) {
case 0:
if (first != 0) {
Imagename[0].setImageResource(first);
}
FirstColumnComputer.add(a);
FirstColumnComputerFAMILY.add(b);
break;
case 1:
if (first != 0) {
Imagename[1].setImageResource(first);
}
SecondColumnComputer.add(a);
SecondColumnComputerFAMILY.add(b);
break;
case 2:
if (first != 0) {
Imagename[2].setImageResource(first);
}
ThirdColumnComputer.add(a);
ThirdColumnComputerFAMILY.add(b);
break;
case 3:
if (first != 0) {
Imagename[3].setImageResource(first);
}
FourColumnComputer.add(a);
FourColumnComputerFAMILY.add(b);
break;
case 4:
if (first != 0) {
Imagename[4].setImageResource(first);
}
FifthColumnComputer.add(a);
FifthColumnComputerFAMILY.add(b);
break;
case 5:
FirstColumnPlayer.add(a);
FirstColumnPlayerFAMILY.add(b);
break;
case 6:
SecondColumnPlayer.add(a);
SecondColumnPlayerFAMILY.add(b);
break;
case 7:
ThirdColumnPlayer.add(a);
ThirdColumnPlayerFAMILY.add(b);
break;
case 8:
FourColumnPlayer.add(a);
FourColumnPlayerFAMILY.add(b);
break;
case 9:
FifthColumnPlayer.add(a);
FifthColumnPlayerFAMILY.add(b);
break;
}
Cards.remove(Random);
long sleepMax = 1000L;
Random r = new Random();
long delay = (long) (r.nextDouble() * range);
Thread.sleep(delay);
}
SentTheLinkedList();
}

Method to check higher precendence of operators, Is there a smarter way to do this?

Here's a method I wrote to check which operator has the highest precedence, now my question is: is there any other way I can do this? I have been testing this one and it works fine, but I'm pretty sure there should be room for improvement. What do you think?
static boolean hasHigherPrecendence(char top, char current){
String t = String.valueOf(top);
String c = String.valueOf(current);
System.out.println(t);
System.out.println(c);
switch (t) {
case "-":
if ( c.equals("-") || c.equals("+") )
return false;
break;
case "+":
if ( c.equals("-") || c.equals("+") )
return false;
break;
case "/":
if ( !c.equals("*") || !c.equals(t) || !c.equals("%") )
return false;
break;
case "*":
if ( !c.equals("%") || !c.equals(t) || !c.equals("/"))
return false;
break;
case "%":
if (c.equals(t) || c.equals("*") || c.equals("/"))
return false;
break;
default:
throw new IllegalArgumentException("Operator unknown: " + t);
}
return true;
}
If it were me I would rank the operators in a function (note, the values I chose are not necessarily the ones you should use ...):
private static final int rankOperator(char op) {
switch (op) {
case '-' : return 0;
case '+' : return 0;
case '/' : return 2;
case '*' : return 2;
case '%' : return 4;
}
throw new IllegalStateException("Unknown operator " + op);
}
public boolean hasHigherPrecedence(char top, char current) {
return rankOperator(top) > rankOperator(current);
}
Apart of using maps, arrays, functions... you can reduce your code using the concatenating the cases with the same behaviour:
static boolean hasHigherPrecendence(char top, char current){
String t = String.valueOf(top);
String c = String.valueOf(current);
System.out.println(t);
System.out.println(c);
switch (t) {
case "-":
case "+":
if ( c.equals("-") || c.equals("+") )
return false;
break;
case "/":
case "*":
case "%":
if (c.equals("%") || c.equals("*") || c.equals("/"))
return false;
break;
default:
throw new IllegalArgumentException("Operator unknown: " + t);
}
return true;
}
static boolean hasHigherPrecendence(char top, char current){
Map<Character,Integer> map = new HashMap<>();
map.put('+',new Integer(1));
map.put('-',new Integer(1));
map.put('*',new Integer(2));
map.put('/',new Integer(2));
map.put('%',new Integer(3));
if( map.get(top)==null ){
throw new IllegalArgumentException("Operator unknown: " + top);
}
if( map.get(current)==null ){
throw new IllegalArgumentException("Operator unknown: " + current);
}
if(map.get(t) >= map.get(c)){
return true;
}else{
return false;
}
}

Why isn't this public String function working?

It is saying that it must return a string but I don't see anything wrong with it? I think numericDayOfWeek should be working fine?
public String getDayOfWeek(){
if(numericDayOfWeek==0){
return "Saturday";
}
if(numericDayOfWeek==1){
return "Sunday";
}
if(numericDayOfWeek==2){
return "Monday";
}
if(numericDayOfWeek==3){
return "Tuesday";
}
if(numericDayOfWeek==4){
return "Wednesday";
}
if(numericDayOfWeek==5){
return "Thursday";
}
if(numericDayOfWeek==6){
return "Friday";
}
}
Here is the full code
public class DayOfWeek {
int myMonth, myDayOfMonth, myYear, myAdjustment, numericDayOfWeek;
public DayOfWeek(int month, int dayOfMonth, int year){
myMonth = month;
myDayOfMonth = dayOfMonth;
myYear = year;
}
public int getNumericDayOfWeek(){
if(myMonth==1){
myAdjustment = 1;
if(myYear%4==0){
myAdjustment-=1;
}
}
if(myMonth==2){
myAdjustment = 4;
if(myYear%4==0){
myAdjustment-=1;
}
}
if(myMonth==3){
myAdjustment = 4;
}
if(myMonth==4){
myAdjustment = 0;
}
if(myMonth==5){
myAdjustment = 2;
}
if(myMonth==6){
myAdjustment = 5;
}
if(myMonth==7){
myAdjustment = 0;
}
if(myMonth==8){
myAdjustment = 3;
}
if(myMonth==9){
myAdjustment = 6;
}
if(myMonth==10){
myAdjustment = 1;
}
if(myMonth==11){
myAdjustment = 4;
}
if(myMonth==12){
myAdjustment = 6;
}
int fourDivides = myYear / 4;
numericDayOfWeek = myAdjustment + myDayOfMonth + (myYear-1900) + fourDivides;
return numericDayOfWeek;
}
public String getDayOfWeek(){
if(numericDayOfWeek==0){
return "Saturday";
}
if(numericDayOfWeek==1){
return "Sunday";
}
if(numericDayOfWeek==2){
return "Monday";
}
if(numericDayOfWeek==3){
return "Tuesday";
}
if(numericDayOfWeek==4){
return "Wednesday";
}
if(numericDayOfWeek==5){
return "Thursday";
}
if(numericDayOfWeek==6){
return "Friday";
}
}
public int getMonth(){
}
public String getMonthString(){
}
public int getDayOfMonth(){
}
public int getYear(){
}
}
Sotirios is correct, but a better solution here would be to use a case statement:
switch(numericDayOfWeek)
{
case 0:
return "Saturday";
case 1:
return "Sunday";
case 2:
return "Monday";
case 3:
return "Tuesday";
case 4:
return "Wednesday";
case 5:
return "Thursday";
case 6:
return "Friday";
default:
return "Error";
}
If none of the conditions passes, ie. they all evaluate to false, the method wouldn't return anything. Add a default return at the end
public String getDayOfWeek(){
if(numericDayOfWeek==0){
return "Saturday";
}
if(numericDayOfWeek==1){
return "Sunday";
}
if(numericDayOfWeek==2){
return "Monday";
}
if(numericDayOfWeek==3){
return "Tuesday";
}
if(numericDayOfWeek==4){
return "Wednesday";
}
if(numericDayOfWeek==5){
return "Thursday";
}
if(numericDayOfWeek==6){
return "Friday";
}
return "Error";
}
The compiler considers all paths. If none if the if statements was executed it wouldn't have anything to return. In that case, it won't be able to compile because the method wouldn't guarantee the contract specified by its definition, ie. to return a String.
Follow the comments or the other answer on how to possibly makes this perform better or make it easier to read (switch-case).
This should work:
public String getDayOfWeek(){
if(numericDayOfWeek==0){
return "Saturday";
}
else if(numericDayOfWeek==1){
return "Sunday";
}
else if(numericDayOfWeek==2){
return "Monday";
}
else if(numericDayOfWeek==3){
return "Tuesday";
}
else if(numericDayOfWeek==4){
return "Wednesday";
}
else if(numericDayOfWeek==5){
return "Thursday";
}
else if(numericDayOfWeek==6){
return "Friday";
}
else{
return "Error";
}
}
The reason for the compiler error is that the compiler cannot be certain that your code will always return a String from your method.
In the event that numericDayOfWeek is not in the range of 0 to 6, your function does not specify what value should be returned, and there is no way for the compiler to know or guarantee that numericDayOfWeek will always be within the desired range.
Unfortunately, the compiler is limited in its ability to ensure a return statement even in simple cases. Take the trivial (and useless) method below:
// I have a compiler error!
public boolean testReturn()
{
final boolean condition = true;
if (condition) return true;
if (!condition) return false;
}
The above will result in a compiler error saying the method must return a type of boolean. We could easily fix it by changing the second if statement to be an else clause since that is one of the few ways that allow the compiler to ensure one or the other blocks of code are guaranteed to be executed.
// I compile!
public boolean testReturn()
{
final boolean condition = true;
if (condition) return true
else return false;
}
The rules are that a method with a return type must not complete normally and must instead complete abruptly (abruptly here indicating via a return statement or an exception) per JLS 8.4.7. The compiler looks to see whether normal termination is possible based on the rules defined in JLS 14.21 Unreachable Statements as it also defines the rules for normal completion.
In the case of your specific example, I would suggest considering throwing an IllegalArgumentException as the last line of your method and replacing your if statement with a switch statement. E.g.
public String getDayOfWeek()
{
switch(numericDayOfWeek)
{
case 0: return "Saturday";
case 1: return "Sunday";
case 2: return "Monday";
case 3: return "Tuesday";
case 4: return "Wednesday";
case 5: return "Thursday";
case 6: return "Friday";
}
throw new IllegalArgumentException("numericDayOfWeek is out of range: " + numericDayOfWeek);
}
You can also throw the exception in a default clause of the switch statement, but in this case I would say that is just a matter of personal preference and I prefer outside of the switch here.

Categories

Resources