This question already has answers here:
Switch statement just returning the last case
(4 answers)
Closed 3 years ago.
I'm debugging my application in IntelliJ and it seems like my code is going into 2 switch statements instead of 1.
My code looks like this:
final String CASE_1 = "case_1";
final String CASE_2 = "case_2";
switch(CASE): {
CASE_1: {
// do something
}
CASE 2: {
// do something
}
}
My application executes the code that's in both cases.
Is there any reason why the code would go into both cases?
(I'm intentionally not pasting my actual code since it's impossible to reproduce locally without creating the whole structure of the project)
Put a break after each case, otherwise it forwards to the next case.
public class Main {
public static void main(String args[]) {
final String CASE_1 = "case_1";
final String CASE_2 = "case_2";
String CASE = "case_1";
switch(CASE){
case CASE_1:{
System.out.println("Case 1 Found");
break; //Put a break here if you don't want the code to execute for the next case as well.
}
case CASE_2:{
System.out.println("Case 2 Found");
}
}
}
}
Because you dont end the case
public void runTest(String CASE) {
switch (CASE) {
case CASE_1:
// code block
break;
case CASE_2:
// code block
break;
default:
break;
}
}
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
This is just something im trying out, i just recently started coding in java would like some help. Would like to ask user to pick their favorite movie, then take their input and use if statements to give different responses to each response.
import java.util.Scanner;
public class miniFFF {
public static void main (String[]p) {
System.out.println("What is your favourite movie? pick from the answers below:");
System.out.println("a");
System.out.println("b");
System.out.println("c");
System.out.println("d");
System.out.println("e");
answer();
//ifStatements();
System.exit(0);
}
public static String answer() {
String favMovie;
Scanner test = new Scanner(System.in);
favMovie = test.next();
if(favMovie == "a") {
System.out.println("1234");
}
else if (favMovie == "b") {
System.out.println("123");
}
return favMovie;
}
}
Using switch will make your code much readable.
switch (favMovie){
case "a": //do for a
break;
case "b" //do for b
break;
default: //no match
}
Java enum was designed for when you have a finite set of options. As good practice it will be a better option over string literal
I don't really see a question there and your code seems, I could point two thing I might do differently tho.
One I would use equalIgnoreCase instead of == in case someone doesn't put the correct capitalization (Also add a general case)
Also putting the method outside main seems to be better practice.
I'm trapped within this certain predicament of mine and I would gladly accept any suggestion. So here it is:
I'm currently working in a method where a certain variable is assigned a specific value in the beginning part of the method. During the course of the method, that variable is used as a parameter by an external component which basically returns a result code. In one of those result codes, I have to change the value of the prior mentioned variable and repeat the whole process using the new value. The concept is as follows but I have simplified it as much as possible:
public void myMethod (String args[]) {
String server;
server = "some value";
switch (someExternalOperation(server)) {
case 1:
//process....
break;
case 2:
server = "new value";
//repeat myMethod using new value of server String variable
break;
}
}
public int someExternalOperation (String str) {
//after several operation
return 1; //example purposes
}
By the way, I have checked and researched things like goto and other alternative. I may have overlooked some results and ended up asking here. Any help would be much appreciated. Thank you.
One simple option is to have a private overload taking the server parameter - then you can call it recursively:
public void myMethod(String args[]) {
myMethod(args, "some value");
}
private void myMethod(String[] args, String server) {
switch (someExternalOperation(server)) {
case 1:
// process....
break;
case 2:
myMethod(args, "new value");
break;
}
}
You need to make sure that isn't going to recurse infinitely, of course.
Another option would be to just have a loop inside your method:
public void myMethod (String args[]) {
String server = "some value";
while (true) { // Or ideally a different condition...
switch (someExternalOperation(server)) {
case 1:
// process....
// Done! Exit the method...
return;
case 2:
server = "new value";
// We'll now continue to the next iteration of the loop
break;
default:
// ?
}
}
}
I figured a way instead to address. Thanks everyone for reading. I'll just simply use the external operation and check if it will return case 2.
public void myMethod (String args[]) {
String server;
server = "some value";
if (someExternalOperation(server) == 2)
server = "new value";
switch (someExternalOperation(server)) {
case 1:
//process....
break;
}
}
public int someExternalOperation (String str) {
//after several operation
return 1; //example purposes
}
Thanks for your help anyway.
I am working with some Java code that is comprised of a switch statement comparing strings. There are about 5 cases before learning that more needed to be added.
In fact I would need to add 64 more cases (4 groups of 16 similarly spelled values) and due to the nature of the strings was hoping to use regex to not need so many statements. For example, the first group of possible values is "Section ## Stuff", the second group "Section ## Stuff XYZ", and so on; where the ## is any number between 1 and 16.
To clarify, instead of adding a case for each string, I wanted to regex out the type, and then call the appropriate function, etc.
While this is all working correctly, I am worried that it will be hard for another developer to make sense of what is happening, as I have essentially combined regex if-statements and switch statements. I also cannot stand having very large switch statement lists.
What is the better option (readability vs eloquence, etc.), and is it possible to somehow use regex with my switch statement? Also, I don't think there would be any significant performance hit, but if there is, it would be nice to know. :)
Code below is an example as I cannot provide the real code.
What I want to do:
if (str.matches("Section ([1-9]|1[0-6]) Stuff") {
//do something with the number provided in string
} else if (str.matches("Section ([1-9]|1[0-6]) Stuff 2") {
//do something else with the number provided in the string
} else {
switch (str) {
case PARAM_VALUE_1:
doSomething1();
break;
case PARAM_VALUE_2:
doSomething2();
break;
...
...
default:
break;
}
}
OR -
switch (str) {
case PARAM_VALUE_1:
doSomething1();
break;
case PARAM_VALUE_2:
doSomething2();
break;
...
...
case "Section 1 Stuff":
//do something for section 1
break;
case "Section 2 Stuff":
//do something for section 2
break;
...
... (64 cases later)
default:
break;
}
}
Note: I cannot redesign the way the string comes in; it comes from another subsystem and it is what it is.
Thanks for your help!
For this case, you might consider using Java enums, exploiting their overriding functionality.
enum MyEnum {
SectionOne("Section ([1-9]|1[0-6]) Stuff") {
#Override
public void doSomething() {
// implementation for section one when regex matches
}
}, SectionTwo("Section ([1-9]|1[0-6]) Stuff 2") {
#Override
public void doSomething() {
// implementation for section two when regex matches
}
}, Param1("ParamValue1") {
#Override
public void doSomething() {
// implementation for param 1
}
}, Param2("ParamValue2") {
#Override
public void doSomething() {
// implementation for param 2
}
};
private final Pattern regex;
private MyEnum(String strRegex) {
this.regex = Pattern.compile(strRegex);
}
public abstract void doSomething();
public static MyEnum valueFor(String value) {
for (MyEnum myEnum : MyEnum.values()) {
if(myEnum.regex.matcher(value).matches()) {
return myEnum;
}
}
return null;
}
}
You can see the IDEOne demo.
I have a problem returning a result of String type in Java.
Here is the whole code
import java.util.*;
public class Multiplication
{
static Random randomNumbers = new Random();
static Scanner input = new Scanner(System.in);
static int answer;
public static void multiplication()
{
createQuestion(); //display first question
int guess; //student's answer
System.out.print("Your answer is (-1 to quite): ");
guess = input.nextInt();
while(guess != -1)
{
checkAnswer(guess);
System.out.print("Your answer is (-1 to quite): ");
guess = input.nextInt();
}
} //end method multiplication
//create new question
public static void createQuestion()
{
int num_1 = randomNumbers.nextInt(10);
int num_2 = randomNumbers.nextInt(10);
answer = num_1 * num_2;
System.out.printf("How much is %d times %d?\n", num_1, num_2);
}//end method createQuestion
public static String createResponse(boolean correct)
{
if (correct)
switch(randomNumbers.nextInt(4))
{
case 0:
return ("Very good!");
case 1:
return("Excellent!");
case 2:
return("Nice work!");
case 3:
return ("Keep the good work");
} //end switch
//otherwise, assume incorrect
switch(randomNumbers.nextInt(4))
{
case 0:
return("No. Please try again.");
case 1:
return("Wrong. Try once more.");
case 2:
return("Don't give up!");
case 3:
return("No. Keep trying.");
}//end switch
}//end method createResponse
//check in the student answer correctly
public static void checkAnswer(int guess)
{
if(guess != answer)
{
System.out.println(createResponse(false));
}
else
{
System.out.print(createResponse(true));
createQuestion();
}
}//end method checkAnswer
}//end class Multiplication
And here is the main method
public class MultiplicationTest {
public static void main(String[] args) {
Multiplication app = new Multiplication();
app.multiplication();
}
}
The problem is in the createResponse(boolean correct) method. Here JDE is saying that "This method must return a result of type String". I have mentioned there String type return. But the program is not being executed. Showing a red line under the method createResponse(boolean correct).
Does anybody where I have messed up?
Thanks in advance!
The compiler cannot assert that your method returns a String.
This is because your switch-case may fail to return anything.
You can satisfy the compiler by placing a
return null;
at the end of your method.
The method createResponse might not always reach a return statement in your code. If none of the cases in your second switch statement applies, it will reach the bottom of the code block without returning.
Just make sure you return something at the end of the method (or find another nice solution):
return "";
}//end method createResponse
It's because if none of the conditions in either of the switch statements were met there would be nothing to return. Try something like:
public static String createResponse(boolean correct)
{
String result = null;
if (correct)
switch(randomNumbers.nextInt(4))
{
case 0:
result = "Very good!";
// Insert the rest of the code here, assigning to result rather than returning as above.
return result;
}
you are missing the 'else' part for the 'if' and the 'default' case for the 'switch-case' in the createResponse method.
edit:
ok, the 'else' is not necessary, but I missed that in the first place. the indentation of the second 'switch' is confusing. please use parentheses to avoid this.
Furthermore, the compiler believes that it could happen that none of the 'case' branches will get executed since it is not aware of the nextInt returning Integers in the range of 0..3. you'll need to add the default case to satisfy the compiler.
Compiler is not smart enough yet to know that nextInt(4) may return only 0,1,2 and 3 so it assumes that for case like 5 you current code will not return anything, but if method declares that it will return some value must guarantee that some value will always be returned.
To solve this problem you can change case 3: to default:. This would make compiler assume that even for cases which are not 0,1,2 some value will be returned.
Also it seems that your code would be cleaner if you would use else and additional curly brackets like
public static String createResponse(boolean correct) {
if (correct){
switch (randomNumbers.nextInt(4)) {
case 0:
return ("Very good!");
case 1:
return ("Excellent!");
case 2:
return ("Nice work!");
default:
return ("Keep the good work");
}
} else {
switch (randomNumbers.nextInt(4)) {
case 0:
return ("No. Please try again.");
case 1:
return ("Wrong. Try once more.");
case 2:
return ("Don't give up!");
default:
return ("No. Keep trying.");
}
}// end switch
}// end method createResponse
BTW you can simplify your code a little by using arrays which would store your responses. This way your code could look like
private static String[] good = { "Very good!",
"Excellent!",
"Nice work!",
"Keep the good work" };
private static String[] bad = { "No. Please try again.",
"Wrong. Try once more.",
"Don't give up!",
"No. Keep trying." };
public static String createResponse(boolean correct) {
if (correct)
return good[randomNumbers.nextInt(4)];
else
return bad[randomNumbers.nextInt(4)];
}
or even
public static String createResponse(boolean correct) {
return correct ? good[randomNumbers.nextInt(4)]
: bad[randomNumbers.nextInt(4)];
}
So here is a sample code :
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("Please type in a number");
Scanner in = new Scanner(System.in);
switch (in.nextInt()){
case 1:
save(in);
break;
case 2:
System.out.println(value);
break;
default:
System.out.println("Default case");
break;
}
in.close();
}
public static String save(Scanner in){
System.out.println("Type in a word");
String value = in.next();
return value;
}
}
In this particular situation all I am trying to do here is to have access to the value that was stored in case 1.
switch statement in all c-like languages including java is very general. It jumps to label according to the value of switch variable and then continues until break statement appears.
I am not sure what did you meant in your long explanation but in following example:
switch(op) {
case ONE:
foo();
case TWO:
bar();
break;
case THREE:
aaa();
qqq();
break;
}
op == ONE first method foo() will be called, then the flow will arrive to block of TWO because no break statement was written in ONE, so bar() will be called. However then the break statement will jump the flow to code that appears just after the switch.
This is a short explanation. For more details find a good book or tutorial and read chapter about switch statement.