I wrote the following code but get the following compile error:
The local variable dirArrow may not have been initialized. Note that
a problem regarding missing 'default:' on 'switch' has been
suppressed, which is perhaps
related to this problem
//return the ID of the robot and arrow of his facing direction
public String toString(){
char dirArrow;
switch (direction) {
case UP: dirArrow= '^';
case RIGHT: dirArrow= '>';
case DOWN: dirArrow= 'V';
case LEFT: dirArrow= '<';
break;
}
return (Integer.toString(RoboID) + dirArrow);
}
You need to initialize your dirArrow variable like:
char dirArrow = ' ';
switch (direction) {
Read why local variable should be initialized.
Note: also you need to add a break statement to the end of each case block like:
case UP: {
dirArrow= '^';
break;
}
You have two problems there
You haven't initialize the method local variable dirArrow, initialize it like char dirArrow = ' ';
You don't have break at the end of each case. If you don't add break at the end of each case, for the first case, it will run all the case statements below that.
switch (direction) {
case UP: dirArrow= '^'; break;
case RIGHT: dirArrow= '>'; break;
case DOWN: dirArrow= 'V'; break;
case LEFT: dirArrow= '<'; break;
}
either initialise the variable at declaration: char dirArrow = 0; or add a default block:
switch (direction) {
case UP: dirArrow= '^';
case RIGHT: dirArrow= '>';
case DOWN: dirArrow= 'V';
case LEFT: dirArrow= '<';
break;
defalut: dirArrow = 0;
}
BTW: for your code to work as expected, you should add a break after each case statement:
switch (direction) {
case UP: dirArrow= '^'; break;
case RIGHT: dirArrow= '>'; break;
case DOWN: dirArrow= 'V'; break;
case LEFT: dirArrow= '<'; break;
defalut: dirArrow = 0;
}
its very much clear from the error that you have to initialize the local variable like ''
like
char dirArrow='';
A better solution is to change the enum
enum Direction {
UP("^"), DOWN("v"), LEFT("<"), RIGHT(">");
public final String arrow;
private Direction(String arrow) {
this.arrow = arrow;
}
}
// in your Robot class.
public String toString(){
return RoboID + direction.arrow;
}
BTW I would use roboID for a field name.
You haven't said what you want to happen if the direction isn't any of those values. Maybe that's currently the full set of directions, but in the future it may not be - and fundamentally the Java compiler doesn't check that you've covered every enum possibility. (You're also missing break statements, as noted by other answerers.)
Personally I'd change the approach and get rid of the switch entirely: add a toChar method to Direction, and then you can just use:
return Integer.toString(RoboID) + direction.toChar();
Your enum constructor would take the character to use as well, so it would be very easy to implement.
Much cleaner, IMO. The only downside is that it ties your character representation to the Direction enum which may be intended to be UI-neutral. If that's the case, I'd have a Map<Direction, Character> instead, and you can use it very simply:
return Integer.toString(RoboID) + DIRECTION_CHARS.get(direction);
If you want to stick with the switch statement, I wouldn't add an initial value to the variable as others have suggested - I'd throw an exception in the default case:
#Override public String toString() {
char dirArrow;
switch (direction) {
case UP:
dirArrow= '^';
break;
case RIGHT:
dirArrow= '>';
break;
case DOWN:
dirArrow= 'V';
break;
case LEFT:
dirArrow= '<';
break;
default:
throw new IllegalStateException("Unexpected direction! " + direction);
}
return (Integer.toString(RoboID) + dirArrow);
}
That's assuming it really isn't valid to have a direction other than the ones you've listed. Now, if you add a direction and forget to update this method, you'll end up with an exception rather than silent bad data.
The reason to not use a "dummy" initial value for the variable is that it doesn't express your desired behaviour. If you were to describe the method to someone in words, you would never mention that value, unless you really have a default value (e.g. space), in which case it's absolutely the right way to go.
Related
I have this code with the switch statement which I got from this post, and it works absolutely fine:
String getOrdinal(final int day) {
if (day >= 11 && day <= 13) {
return "th";
}
switch (day % 10) {
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}
But if I change it to something like the following, it breaks, as all the cases besides case 1 gets executed:
static String getOrdinal(final int day) {
StringBuilder ordinalBuilder = new StringBuilder();
ordinalBuilder.append("<sup>");
if (day >= 11 && day <= 13) {
ordinalBuilder.append("th") ;
}
switch (day % 10) {
case 1: ordinalBuilder.append("st");
case 2: ordinalBuilder.append("nd");
case 3: ordinalBuilder.append("rd");
default: ordinalBuilder.append("th");
}
ordinalBuilder.append("</sup>");
return ordinalBuilder.toString();
}
This prints 2<sup>ndrdth</sup> when I pass in 2. I tried changing the builder to buffer but I got the same response... Could this be a bug or am I making some mistake?
It's a bug in your code. You forgot to put in a break after each case:
switch (day % 10) {
case 1: ordinalBuilder.append("st"); break;
case 2: ordinalBuilder.append("nd"); break;
case 3: ordinalBuilder.append("rd"); break;
default: ordinalBuilder.append("th"); break;
}
I don't see any bug here, at least not in the way the language is working. The behavior of a switch statement, by design, is that it will start executing statements at the case label which matches the argument, and then continue until the end of the block. So
switch (x) {
case 1:
// do thing 1
case 2:
// do thing 2
case 3:
// do thing 3
default:
// do nothing
}
will do both things 2 and 3 if x is 2, and will do things 1, 2, and 3 if x is 1.
To get the behavior you're probably looking for, end each case with a break:
switch (x) {
case 1:
// do thing 1
break;
case 2:
// do thing 2
break;
case 3:
// do thing 3
break;
default:
// do nothing
break;
}
(strictly speaking the break at the very end is unnecessary, but I often put it in out of habit).
The reason you didn't have this problem in the first code example is that return is like a super-break: it has the same effect as break, namely ending execution within the switch block, but it also ends execution of the whole method.
you need to add a 'break' statement in every switch case.
It was worked previously because you made a return from method...
A "break;" statement separates the cases from one another so in order to execute the statements in a specific case just break the case as soon as it comes to an end.
If you don't use break the compiler thinks that it can continue execution of all the cases up to the end of the program.
The first version returns before continuing on in the case statement. The second version needs a break; statement to get the same behavior.
Luckily with the introduction of switch statements on Java 12 which also introduced
"arrow case" labels that eliminate the need for break statements to
prevent fall through (source).
Therefore the modern version of your code looks like the following:
String getOrdinal(final int day) {
if (day >= 11 && day <= 13) {
return "th";
}
return switch (day % 10) {
case 1 -> "st";
case 2 -> "nd";
case 3 -> "rd";
default -> "th";
};
}
I see this question is over 8 years old, but this answer should help anyone landing on this page.
Firstly lets's understand how switch cases work. In C, C++, Java, JavaScript, and PHP while executing switch statements all the cases following the satisfactory case are executed, unlike in Go where only selected case is executed.
For example:
public class Main
{
public static void main(String[] args) {
int day = 11;
switch (day % 10) {
case 1: System.out.println("st");
case 2: System.out.println("nd");
case 3: System.out.println("rd");
default: System.out.println("th");
}
}
}
Currently, day value is set to 11 and hence very first case satisfy the condition, and hence all below cases would be executed. The output should look like the one below:
st
nd
rd
th
Now let's change day value to 13 resulting in the third case to satisfy the condition and hence below output is obtained:
rd
th
Hence if you want to break the code after first satisfactory case is found then put break; condition in the end. In the code mentioned in the question return; does the job of breaking the code.
Also, most of the novice java programmers believe that SWITCH statements are syntactical sugar to IF statements wherein programmers don't have to repetitively mention conditions. But that's not the case as IF's are meant to exit after the execution of satisfactory condition while SWITCH still continues execution.
Switch cases can be utilized to achieve the purpose like one mentioned in below example:
wherein
for Grade A "Excellent!" should be printed
for Grade B and C "Well done" should be printed
for Grade D "You passed \n Try hard next time" should be printed
for Grade F "Try hard next time" should be printed
and if not a valid case i.e grade is found than "Invalid Grade" should be printed.
public class Test {
public static void main(String args[]) {
// char grade = args[0].charAt(0);
char grade = 'C';
switch(grade) {
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Try hard next time");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Add a break statement at the end of the every line in each case or just use the return statement.
So I'm writing a program that randomly generates a maze and then finds a solution for it. Part of my code includes a backtracking algorithm where I move back if I hit a dead end.
Everytime I move, I record the move ("N" for North, "NE" for Northeast, on and on) in a stack. For the backtracking, I pop the top element of the stack and use a switch statement to move the opposite direction of the direction popped.
When I try to compile my code, it gives me an error that the Stack object popped cannot be converted to int, but I have seen String used for switch statements in other programs. I thought the toString method would automatically convert the object to String for the switch statement. I have tried manually using toString with the popped value as the parameter but that didn't work either. Here is the code and error message.
switch(visitStack.pop())
{
// have to backtrack the opposite direction i previously went
case "N": nowR++;
visited[nowR][nowC] = 'N';
break;
case "NE": nowR++;
nowC--;
visited[nowR][nowC] = 'N';
break;
case "E": nowC--;;
visited[nowR][nowC] = 'N';
break;
case "SE": nowR--;
nowC--;
visited[nowR][nowC] = 'N';
break;
case "S": nowC--;
visited[nowR][nowC] = 'N';
break;
case "SW": nowR--;
nowC++;
visited[nowR][nowC] = 'N';
break;
case "W": nowC++;
visited[nowR][nowC] = 'N';
break;
case "NW": nowR++;
nowC++;
visited[nowR][nowC] = 'N';
break;
}
The blued out portion has personal details.
For java versions below 7 it wont support Strings in Switch Case
Alternative would be else if ladder to compare strings using .Equals() method
or
you can Use Enums in Switch Case
I am expecting my input to be one of three groups of chars and need to decide what to do with it based on which group it falls in. I'm trying to figure out how to define a switch with multiple cases to do this. Here is what I have so far:
while(in.hasNextChar())
{
char test = in.nextChar();
List<Signal> out = new List<Signal>(0);
switch(test)
{
case '1','0','x','X':
out.add(fromString(test));
break;
case ' ','/t':
break;
default:
throw new ExceptionLogicMalformedSignal;
}
}
return out;
}
You have the syntax wrong. You need to take advantage of fall-through:
switch(test) {
case '1':
case '0':
case 'x':
case 'X':
out.add(fromString(test));
break;
case ' ':
case '\t':
break;
default:
throw new ExceptionLogicMalformedSignal;
}
A case is just a label, very similar to what you'd use with a goto (which is essentially what is happening behind the scenes). It's not a statement, since it does nothing itself — it just names an address. So if test is '0', it can happily continue through the 'x' and 'X' cases to reach the actual statement code since there's not anything being done by those labels. Only break "ends" a case.
You can actually insert code between cases even without a break:
switch(test) {
case '1':
System.out.println("This is printed by case '1'");
case '0':
System.out.println("This is printed by both case '1' and case '0'");
break;
case 'x':
case 'X':
System.out.println("This is only printed by the Xs");
break;
default:
break;
}
I was answering a Java test and come across the question:
Which of the following statements is true?
A. In an assert statement, the expression after the colon ( : ) can
be any Java expression.
B. If a switch block has no default, adding an assert default is considered appropriate.
C. In an assert statement, if the expression after the colon ( : ) does not have a
value, the assert's error message will be empty.
D. It is appropriate to handle assertion failures using a catch clause.
The right answer is B. To be honest, I answered that question by excluding another obviously wrong cases, but I can't get the point of that question actually. Could anyone explain why it is true? Where can it be helpful?
I guess it means you should protect yourself from missing a switch case.
Say you have an enum Color {red, green} and this switch in the code:
switch(color) {
case red:
doSomethingRed();
break;
case green:
doSomethingGreen();
break;
}
If in the future you add a new color blue, you can forget to add a case for it in the switch.
Adding failing assert to the default case will throw AssertionError and you will discover your mistake .
switch(color) {
case red:
doSomethingRed();
break;
case green:
doSomethingGreen();
break;
default:
assert false : "Oops! Unknown color"
}
This depends on the case but the way I see it
// Consider expecting only 1,2 or 3 as switch case
switch(x)
{
case 1:
// operations
break;
case 2:
// operations
break;
case 3:
// operations
break;
default: assert false : "Input should be between 1-3";
}
Might be convenient as any other input you might receive can be perceived as a faulty input.
Using assert false in switch block's default is applicable in the public method context e.g.
public void methA(int x) throws Exception {
if(x!=1 && x!=2 && x!=3)
throw new IllegalArgumentException("from Exception: x should be between 1,2 and 3");
switch(x)
{
case 1: doSomething(); break;
case 2: doSomething(); break;
case 3: doSomething(); break;
default: assert false : "from default: x should be between 1,2 and 3";
}
}
If the switch block is used in a public method, then checking the value of the argument x is already handled by an exception before the switch statement.
So, even when you use the assert false in default, that code is never reachable, since the assumption that x is 1,2 or 3 is always true. If not true, it is already handled by the IllegalArgumentException before the switch default. So basically, the assumption that switch-default will never be reached is always true. Hence it is appropriate in the context of public method.
I implemented a font system that finds out which letter to use via char switch statements. There are only capital letters in my font image. I need to make it so that, for example, 'a' and 'A' both have the same output. Instead of having 2x the amount of cases, could it be something like the following:
char c;
switch(c){
case 'a' & 'A': /*get the 'A' image*/; break;
case 'b' & 'B': /*get the 'B' image*/; break;
...
case 'z' & 'Z': /*get the 'Z' image*/; break;
}
Is this possible in java?
You can use switch-case fall through by omitting the break; statement.
char c = /* whatever */;
switch(c) {
case 'a':
case 'A':
//get the 'A' image;
break;
case 'b':
case 'B':
//get the 'B' image;
break;
// (...)
case 'z':
case 'Z':
//get the 'Z' image;
break;
}
...or you could just normalize to lower case or upper case before switching.
char c = Character.toUpperCase(/* whatever */);
switch(c) {
case 'A':
//get the 'A' image;
break;
case 'B':
//get the 'B' image;
break;
// (...)
case 'Z':
//get the 'Z' image;
break;
}
Above, you mean OR not AND. Example of AND: 110 & 011 == 010 which is neither of the things you're looking for.
For OR, just have 2 cases without the break on the 1st. Eg:
case 'a':
case 'A':
// do stuff
break;
The above are all excellent answers. I just wanted to add that when there are multiple characters to check against, an if-else might turn out better since you could instead write the following.
// switch on vowels, digits, punctuation, or consonants
char c; // assign some character to 'c'
if ("aeiouAEIOU".indexOf(c) != -1) {
// handle vowel case
} else if ("!##$%,.".indexOf(c) != -1) {
// handle punctuation case
} else if ("0123456789".indexOf(c) != -1) {
// handle digit case
} else {
// handle consonant case, assuming other characters are not possible
}
Of course, if this gets any more complicated, I'd recommend a regex matcher.
Observations on an interesting Switch case trap --> fall through of switch
"The break statements are necessary because without them, statements in switch blocks fall through:"
Java Doc's example
Snippet of consecutive case without break:
char c = 'A';/* switch with lower case */;
switch(c) {
case 'a':
System.out.println("a");
case 'A':
System.out.println("A");
break;
}
O/P for this case is:
A
But if you change value of c, i.e., char c = 'a';, then this get interesting.
O/P for this case is:
a
A
Even though the 2nd case test fails, program goes onto print A, due to missing break which causes switch to treat the rest of the code as a block. All statements after the matching case label are executed in sequence.
From what I understand about your question, before passing the character into the switch statement, you can convert it to lowercase. So you don't have to worry about upper cases because they are automatically converted to lower case.
For that you need to use the below function:
Character.toLowerCase(c);
Enhanced switch/ case / Switch with arrows syntax (Since Java 13):
char c;
switch (c) {
case 'A', 'a' -> {} // c is either 'A' or 'a'.
case ...
}