Unreachable code in swtch statement - java

I have written following method in Java. But I get error message unreachable code on the line containing return (Constants.SUCCESS);
If I comment that line, I do not get error message. Now my doubt is why I do not get error message if I comment that line? There is no return value of SUCCESS to the calling portion if I comment the line. I thought there should be one return statement and there are none if all "if loops" and default is not getting executed. I thought last return statement will execute in any case. I tried return (Constants.SUCCESS) statement at the end also (Commented line), but no luck.
So for returning success, do I need to return success after each "if" loop under every case statements (creating "else" part for each).
static int validateStartAndEndStringOrder(String startStr, String endStr, ArrayList<String> swaraPool, Constants.PatternType ptrnType) {
switch (ptrnType) {
case AROHA_INCREASING: {
if (swaraPool.indexOf(endStr) < swaraPool.indexOf(startStr)) {
System.out.println("End string is before the start String");
return (-1);
}
}
case AROHA_DECREASING: {
if (swaraPool.indexOf(startStr) < swaraPool.indexOf(endStr)) {
System.out.println("End string is before the start String");
return (-1);
}
}
case AVAROHA_INCREASING: {
if (swaraPool.indexOf(endStr) < swaraPool.indexOf(startStr)) {
System.out.println("End string is before the start String");
return (-1);
}
}
case AVAROHA_DECREASING: {
if (swaraPool.indexOf(startStr) < swaraPool.indexOf(endStr)) {
System.out.println("End string is before the start String");
return (-1);
}
}
default: {
System.out.println("Invalid Enumeration Type");
return(-1);
}
return (Constants.SUCCESS);
}
//return (Constants.SUCCESS);
}

switch ... case 1 ... case n ... default covers all control paths (the default will catch all remaining cases). Since you return explicitly out of each one, there's no way program control can go beyond that switch block.
Your compiler is being helpful in emitting the error.
Use break; statements between each case in the switch block to move control flow to the end of the block.

I suspect you want to add a break; at the end of your case blocks. Otherwise the code just runs from top to bottom (like anywhere else in your code)
If you place a break; it will jump outside the switch block which appears to be what you want.
e.g.
case AROHA_INCREASING: {
if (swaraPool.indexOf(endStr) < swaraPool.indexOf(startStr)) {
System.out.println("End string is before the start String");
return (-1);
}
break; // without this, the thread will run the next case: block.
}

You default section contains
{
System.out.println("Invalid Enumeration Type");
return(-1);
}
return (Constants.SUCCESS);
What do you expect?

Related

My else statement doesn't seem to function(JAVA)

import java.util.Scanner;
import static java.lang.System.*;
public class Whativelearned {
enum MyfirstEnum {one, two, three}
public static void main(String[] args) {
Scanner keyboardinput = new Scanner(in);
MyfirstEnum trolley;
char a1;
out.println("Do you pee in the shower"? Y/N");
a1 = keyboardinput.findWithinHorizon(".", 0).charAt(0);
if (a1=='Y'||a1=='y') {
trolley=MyfirstEnum.one;
out.println("Ewwwwwww");
}
if (a1=='N'||a1=='n') {
trolley=MyfirstEnum.two;
out.println("Well somebody isn't being very honest");
}else {
out.println("You're not so keen on following instructions, are you?");
}
keyboardinput.close();
}
}
I expect my else statement to cover all outcomes except for the cases in the if cases.
As I expect it to act as (!(a1=='Y'||(a1=='y'||a1=='n'||a2=='N'))
but when I run it the listing the else statement seems to be executed in all cases.
Try this
if (a1=='Y' || a1=='y') {
trolley=MyfirstEnum.one;
out.println("Ewwwwwww");
} else if (a1=='N' || a1=='n') {
trolley = MyfirstEnum.two;
out.println("Well somebody isn't being very honest");
} else {
out.println("You're not so keen on following instructions, are you?");
}
The else statement is always specific to one if statement. Therefore, your else clause is executed whenever the last if condition is not met.
To execute your clause only when none of the conditions are met, you need to change your if statements to else if like so:
if (a1 == 'y' || a1 == 'Y') {
// ...
} else if (a1 == 'n' || 'a1 == 'N') {
// ...
} else {
// ....
}
Another way to solve this would be using a switch statement. These are used to compare a variable to a set of constants. You can use them like this:
switch (a1) {
case 'y':
case 'Y':
// ...
break;
case 'n':
case 'N':
// ...
break;
default:
// ...
}
Please read up some more about the switch statement before you try it in other situations.
Just write else befor second for loop:
else if (a1=='N'||a1=='n') {
Code execution is best understood by a dry run.
If you do in your code you will find the first if statement is checked and if its true then its corresponding process is executed.
Now control moves down to execute the next if statement. This if statement checks the condition which os mutually exclusive of the above if. if its true (only in case above is false) then its corresponding process is executed and if its false then the else part process is executed.
You need to use if followed by if else followed by else

While loop ends even when the method is not called [Java]

One of the requirements of my project is that the program loops until the user presses the "X" key. I have the method for this, but the program terminates even when the method is not called. Here is my code:
while (terminate == false)
{
// Ask user for input
switch (command)
{
case "I":
{
// Do stuff
}
case "X":
{
terminateProgram();
}
}
}
This is my terminate method:
private static boolean terminateProgram()
{
terminate = true;
return terminate;
}
Even if I enter the "I" key, the loop ends after the case for "I" is completed. "I" works normally if terminateProgram(); is commented. How do I get the loop to stop only when I enter "X"?
You need a break within each case statement.
Read up on fall-through, which is what your current code is doing.
while (!terminate)
{
// Ask user for input
switch (command)
{
case "I":
{
// Do stuff
break;
}
case "X":
{
terminateProgram()
break;
}
default:
// Do something default if no condition is met.
}
}
Then here:
private static void terminateProgram()
{
terminate = true; // if this method simply is to terminate a program
// I'm not quite sure why you need a `terminate` variable
// unless you're using it in another part of the program.
// A simple system.exit(0) would suffice.
System.exit(0);
}

Validation is working too well

I have this validation to check that user input is not blank and is only letters. If it's blank, it catches it, and if if includes digits it also catches it. If I input the 2 characters it asks for, however, it doesn't go through. I'm not sure how to go about this.
private static boolean isValidSt(String aSt) {
boolean result = false;
try {
if (aSt.length() == 2) {
result = true;
} else if (aSt.length() != 2) {
result = false;
}
for (int i=0; i <aSt.length();){
if (!Character.isLetter(i));{
return false;
}
}
return true;
} catch (NumberFormatException nfex) {
if (aSt == null) System.exit(0);
} catch (Exception ex) {
if (aSt == null) System.exit(0);
}
return result;
}
One problem that I can see right of the bat is this:
if (!Character.isLetter(i));{
return false;
}
That semi-colon after your if does not belong there. After checking your conditional statement, if it was true, it will execute until the semi-colon. The return false; isn't part of the if and will ALWAYS be executed.
As David Wallice rightly pointed out, you also never increment the counter in your for-loop, so were it not the case that the program always returned with false in the first iteration, it would indeed get stuck in an eternal loop. A very commonly used syntax for for-loops would be:
for(int i = 0; i < string.length(); i++) { }
A third and final note from me, this time nothin that would give an error, just good form:
You use System.exit(0); to exit the program as result of an exception. The zero you pass as an argument is usually only used when the program shuts down normally. This is a crash as a result of an error, so I'd use 1 or something.
Well, you could use StringUtils methods, isBlank and isAlpha, for validate what you need

Switch Case Error Validation

Just starting Java so it's probably a simple question but couldn't find any questions like mine so figured I would post one.
I am writing a "main menu" with options 1-8. I figured out how to error handle when someone types a number larger than 8 and less than 1 but I can't figure out how to give them an error message if they type a character or letter...
while(menuChoice != 8)
{
//main menu that loops
switch(menuChoice)
{
case 1:
//code
break;
case 2:
//code
break;
case 3:
//code
break;
case 4:
//code
break;
case 5:
//code
break;
case 6:
//code
break;
case 7:
//code
break;
case 8:
//code
break;
default:
System.out.println("Error: Invalid Menu Selection.");
}
}
Assuming this compiles, what you're asking would be impossible. You're switching on a number, so you can't check if the number is a character. Your code wouldn't compile if that were possible.
You should take the user input as a String and validate the String. If the String has non-numeric values in it, then throw an error. If it doesn't, convert it to a number then execute your switch.
A better design would be to have a validation layer. Once the input is validated, just assume it's valid thereafter.
Pseudocode:
String input = //
if (containsNonNumerics(input))
throw error
inputAsInt = castToInt(input)
if (outOfRange(inputAsInt)
throw error
switch //your current code goes here
First off, having that while loop is not going to give you the functionality that you want. You should look into how to use KeyAdapter in order to be able to receive input events from the keyboad, e.g. a number being pressed, and then you can validate that it is actually a number, and if it is you can then use your switch statement to determine the proper code to execute.
I am guessing that menuChoice is a character. In which case, you can either do a manual check that
if('0' <= mc && mc <= '9') {
// do your regular checks
}
If it is a string then do a
try {
Integer.parseInt(mc)
} catch (NumberFormatException e) { // Not a number. Do your error reporting stuff }
HTH.
Switch statment work only with numeric types (int, byte, char, short). If you try add in switch anything else the compailer wouldent allowe you in general. But if you somehow (cating or other way) want to add in switch statment varible you must befor check it with if statment if the varible is type that you want.
Example:
if(var instanceof String){
System.out.println("Error we don't acceped type string");
}
else{
switch(var){
....
}
}
Use this function before entering into while loop and display the error message.
public static boolean isNumeric(String str)
{
NumberFormat formatter = NumberFormat.getInstance();
ParsePosition pos = new ParsePosition(0);
formatter.parse(str, pos);
return str.length() == pos.getIndex();
}
int menuChoice ;
//Now get input from customer in menuChoice
//Your logic goes herr... example menuChoice = ..whateverinput
//After the input is captured then validate
if(menuChoice <1 || menuChoice >8 )
{
//main menu that loops
switch(menuChoice)
{
case 1:
//code
break;
case 2:
//code
break;
case 3:
//code
break;
case 4:
//code
break;
case 5:
//code
break;
case 6:
//code
break;
case 7:
//code
break;
case 8:
//code
break;
default:
System.out.println("Error: Invalid Menu Selection.");
}
else {
System.out.println("Please Enter Valid Entry");
}

How does position of break; is making a difference in output?

I was working upon a program when i noticed something weird in its output behaviour :
Getting required output :
while ((str = input.readLine()) != null)
{
if(str.contains("sometext"))
{
while(str.contains("some_diff_text")==false)
{
if(str.contains("something"))
break;
else
{
//my code;
}
}
break; //difference in output because of this break position
}
}
Not Getting required output :
while ((str = input.readLine()) != null)
{
if(str.contains("sometext"))
{
while(str.contains("some_diff_text")==false)
{
if(str.contains("something"))
break;
else
{
//my code;
}
}
}
break; //not giving me the required output
}
Can someone explain me why there is a difference in the output behaviour ?
You moved the break out of the if in the second snippet, so it breaks out of the loop no matter what.
In the first code snippet, the second break is inside the outer if statement. The outer while loop will break only when the outer if condition is true.
In the second code snippet, the second break follows the outer if statement. Whether or not the outer if condition is true, the outer while loop will break.
In second code:
}
} <--- "this is placed wrong"
break; //not giving me the required output
"} <-- should be present here"
}
That is why correct indentation is important. Indent your code while writing code (but not after writing).
Even in your first code indentation is not correct (Uniform size tab missing), it should be like:
while ((str = input.readLine()) != null)
{
if(str.contains("sometext"))
{// <------
while(str.contains("some_diff_text")==false)
{
if(str.contains("something"))
break;
else
{
//my code;
}
}
break;
}// <------ if ends
}
// 1 2 3 uniform tab spaces ...
Notice each } comes just vertically below { in same line (for example I marked for if in comment). Also each line between code block {...} start at one more tab spaces then { tab spaces.

Categories

Resources