It's not a secret anymore!*
The moose likes Beginning Java and the fly likes switch statement Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "switch statement" Watch "switch statement" New topic
Author

switch statement

adam faith
Greenhorn

Joined: Aug 24, 2002
Posts: 22
Hi,
just working through some code and came across a method with a switch statement in it
public boolean parse(char response)
{
switch(response)
{
case 'y':
case 'Y':
return true;

case 'n':
case 'N':
return false;
default: ;
}
}
but when i compile i keep getting the error
Error #: 466 : method does not return a value at line 57, column 3
i dont understand this from what i can see in the switch a boolean is bieng returned, can somebody help.
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Think what happens when 'response' equals 'Q'. The switch would select the 'default' clause which doesn't do anything, so finally control flow hits the end of the function where no value is returned at all. That's what your compiler is complaining about.
kind regards
adam faith
Greenhorn

Joined: Aug 24, 2002
Posts: 22
Hi Jos
so i added in
default:
throw new IllegalArgumentException("response must be y or n");
and it works, thanks for the pointer
Ron Newman
Ranch Hand

Joined: Jun 06, 2002
Posts: 1056
Of course, if this is a response typed by a user, you'd better handle the IllegalArgumentException somewhere, or else the program will "abruptly terminate" (i.e. crash).


Ron Newman - SCJP 1.2 (100%, 7 August 2002)
 
Don't get me started about those stupid light bulbs.
 
subject: switch statement