Unreachable Code on openURL - java

case "Runetrack":
String inputValue1 = JOptionPane
.showInputDialog("Please enter your username");
if (inputValue1.length() == 0)
JOptionPane.showMessageDialog(null, "You must enter a username.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
openUrl("example.com/" + inputValue1);
break;
For some reason it's telling me that the openUrl(""); isn't 'Unreachable Code'. Why and how do I fix this, thanks.

Looking at the code logic, I'm guessing that the error message and the return are conditional. They need to be put inside the flower braces {} which constitute a code block and in your code, the code block for the if statement.
if (inputValue1.length() == 0) { // if block starts
JOptionPane.showMessageDialog(null, "You must enter a username.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
} // if block ends
openUrl("example.com/" + inputValue1);
break;
The error you're getting is because, any code statement after a return statement will not execute the control is returned back to the calling method. Since the return wasn't conditional(in the code you posted), the 2 lines of code after that became unreachable, thereby giving the error you see. Once you put that inside the if conditional block, it'll work just fine.

You already called return, meaning that the execution pointer jumps out of the method. Therefore the code after the return call cannot be executed.
Edit: Maybe you just forgot to add { and } around the corresponding code.

Related

Why when I have "valid = true;" under How many you want to order, in debug mode it the code works but running it does not?

But if I put it to "valid = false;" it does not work in debug or running.
In fact even running the code, I can't type anything after the "Do you want to order anything else?", no matter if it's in debug or running mode.
Am I missing something? After asking "how many you want to order" and you put in a number after it should ask "do you want to order anything else" which is does but then I can't type and break out of the do while loop. Everything else is working up to that point.
do {
boolean itemValid = true;
while (itemValid) {
System.out.println("Please enter an item name: ");
String enterItem = scnr.nextLine();
if (keepTrack.containsKey(enterItem)) {
System.out.println(keepTrack.get(enterItem));
itemValid = false;
} else {
System.out.println("Sorry we don't exist.");
continue;
}
System.out.println("How many do you want to order?");
int enterQuan = scnr.nextInt();
yourOrder = enterQuan;
valid = false;
}
System.out.println("Do you want to order anything else?");
String yesNo = scnr.nextLine();
if (yesNo.equalsIgnoreCase("n")) {
valid = false;
} else
break;
} while (valid);
Two problems with your code. First, probably unnoticed yet:
do ...
if (keepTrack.containsKey(enterItem)) {
System.out.println(keepTrack.get(enterItem));
itemValid = false;
} else {
System.out.println("Sorry we don't exist.");
continue;
}
When your input is "invalid", you turn into the else branch. The else branch continues the loop. The loop depends on value. Thus: as soon as you start with value=true, and then have an invalid input, you end up with a never-ending loop. Because nothing between the loop start and the continue statement will ever change the conditions that would end the loop.
Your actual question: when you call int enterQuan = scnr.nextInt() that does not consume the "ENTER" that you typed on the console. See here for details.
And there is another problem:
if (yesNo.equalsIgnoreCase("n")) {
valid = false;
} else
break;
}
When the user enters n or N, you go valid=false which ends the outer do-while loop. Thus: when the user enters anything else, the elsepath is taken. What is to be found in the else path? A break. Which also ends the do-while loop.
In other words: your code does exactly what you told it to do: to end the do-while loop, one way or the other.
The real answer is: you need to be much more careful what you put in your code. Each and any character matters. And when you put something into your code for an experiment: remember that it is there, and has effects.

If/else nesting is skipped and goes to the next else statement

In my if/else statement I have two if/else statement and two nested if/else statement. When I run the program and input "s" it would skip the first if statement and then jump to the second if statement and jump back to the while loop and never reaches the nested if/else statement. Now what I intended the program to do is when I input "s" and it runs through the first if statement, in theory, it should run through the nested else statement and the output would be "You can't go that way". The program works when I input the correct input "n". Any suggestions?
while(!input.equals("quit")) {
System.out.println(map.rooms[row][col].name);
System.out.print("<");
input = scan.nextLine().toLowerCase();
if (input.equals("n")) {
if (map.rooms[row][col].isValidExit("n"))
row--;
else
System.out.println("There is no exit that way");
} else if (input.equals("e")) {
if (map.rooms[row][col].isValidExit("e"))
row++;
else
System.out.println("There is no exit that way");
}
}
It's clear that the program will never reach the nested if/else statement when your input is 's' because your main if else statement is just processing the 'n' case and the 'e' case , if want it to process other cases and show the message "There is no exit that way" , then your code should be like this :
while(!input.equals("quit")) {
System.out.println(map.rooms[row][col].name);
System.out.print("<");
input = scan.nextLine().toLowerCase();
if (input.equals("n")) {
if (map.rooms[row][col].isValidExit("n"))
row--;
else
System.out.println("There is no exit that way");
} else if (input.equals("e")) {
if (map.rooms[row][col].isValidExit("e"))
row++;
else
System.out.println("There is no exit that way");
}
else
{
// you should process other cases here like "s"
System.out.println("There is no exit that way");
}
}
I think you are misunderstanding how conditional branches work.
When you say
if (input.equals("n")
{
System.out.println("go north");
}
else if (input.equals("e")
{
System.out.println("go east");
}
It will check if the input equals n or not, and if not, it will check the next branch. It will not go into the branch even if it evaluates to false, because otherwise what would be the point of the conditional branch in the first place? You might as well take it out.
I don't think your "intended" logic would make sense either: if a user hits "s", why would the program check whether north is passable? Your design doesn't seem to make sense from a player's perspective.
If you want to have a case for "s", you can just add it as another branch for when the user does enter "s"
else if (input.equals("s"))
{
System.out.println("go south");
}

Stopping/Resetting a Function in Java if Validation Criteria is not met

I am using this function below to check a value entered in a textbox and if it's valid under the try catch criterias, the function should return a True via the boolean Variable. The program is set up so the final calculation only happens if all my inputs come back as being OK or true in this case.
What I need to get working properly is the return for the try, if the number is not valid the function should stop and get the user to try again, I'm thinking of something like an Exit Sub from VB. My searches have turned up to use a return like I have below, but that just causes an error since the compiler thinks I am trying to return a function result.
There is a tiny bit more to the function, but I cut it out since it is irrelevant; it's pretty much just the bGarage = true; and return bGarage;.
public boolean fnGarageLevel() {//Beginning of Garage Validation Function
int nGarage;
boolean bGarage;
try {//Garage Number Validation Try
nGarage = Integer.parseInt(tfGarage.getText());
if (nGarage != 1 || nGarage != 2 || nGarage != 3 || nGarage != 4) {
JOptionPane.showMessageDialog( null,
"Enter a valid Garage Level, 1, 2, 3 or 4",
"Error",
JOptionPane.ERROR_MESSAGE);
tfGarage.setText("");
tfGarage.grabFocus();
return;
}//End of Error Message
}//End of try
catch (NumberFormatException nfe) {//Beginning of Catch
JOptionPane.showMessageDialog(null,
"Value Entered for Garage is not a Number",
"Error",
JOptionPane.ERROR_MESSAGE);
tfGarage.setText("");
tfGarage.grabFocus();
}//End of Catch for Garage field
bGarage = true;
return bGarage;
}//End of Garage Function
When the try section finishes its running successfully (that is, without catching any exception), the control goes right to the end of catch section or (if it exists) enters the section finally. In this case, the control jumps to bGarage=true sentence when the try ends. Remove the return; statement, it's not necessary.

Predicate Method yes/no/maybe response

I'm trying to write a program where the run method calls a predicate method that asks someone "Do you want to go to a movie tonight?". If the user enters "yes" to the question I want the program to say "Ok. Let's go tonight." If the user enters "no" I want the program to print "That's cool lets go next week." But if the user enters "maybe" I want my program to say "it's a yes or no question" then ask the question again "Do you want to go to go to a movie tonight? " and then wait for a user to enter a response again. The problem I' having is if the user enters "maybe" the program says "it's a yes or no question" then automatically prints "that's fine lets go next week." How do i fix this incorrect logic in my program? This is a question in the chapter focusing on parameter passing in my book. Did I correctly design my program to pass the string value from the run method to the isYesorNo method for what I'm trying to write?
import acm.program.*;
public class MoviesTonight extends ConsoleProgram {
public void run() {
String answer = readLine("do you want to go to a movie tonight?");
if (isYesorNo(answer)) {
println("Ok. Let's go tonight");
} else
println("that's cool let's go next week");
}
private boolean isYesorNo(String response) {
while (!response.equals("yes") && !response.equals("no")) {
println("it's a yes or no question");
break;
}
return (response.equals("yes"));
}
}
I would use a enum for returning the answer if you want something other than true/false, but still a discrete set of values.
For example:
enum Answer {
YES,
NO,
MAYBE
}
Then switch on the enum instead of if/else (down to personal preference, I think a switch statement is cleaner), putting all in a while loop:
boolean yesOrNo = false;
while (!yesOrNo) {
Answer answer = readAnswer("do you want to go to a movie tonight?");
switch (answer) {
case ANSWER.YES:
println("Ok. Let's go tonight");
yesOrNo = true;
break;
case ANSWER.NO:
println("that's cool let's go next week");
yesOrNo = true;
break;
default:
println("it's a yes or no question");
break;
}
}
So basically if the answer is MAYBE, yesOrNo doesn't get set to true so the while loop is executed again when the condition is checked.
The readAnswer method should be a private static helper method and return the correct enum value based on the input string. Either do this by using an if/else or switch statement on the string.
Two things here:
The logic is wrong. If the input is "maybe", then your isYesOrNo will print out "it's a yes or no question", but then returns false, which gives the additional (problematic) output ""that's cool let's go next week".
The break in the loop does not make sense, which is the real problem. The loop should continue unless the condition is meet, it should break out on the first execution of the loop.
In addition to the suggestions already provided, the isYesOrNo method contains a significant error, which is in fact the answer to your base question:
The problem I'm having is if the user enters "maybe" the program says "it's a yes or no question" then automatically prints "that's fine lets go next week." How do i fix this incorrect logic in my program?
return (response.equals("yes"));
If the response is 'maybe', then it does not equal 'yes', and the return will be false -- this is why it immediately prints, "that's cool let's go next week". That is in fact the 'else' condition you supplied for if(isYesOrNo(answer)).
As it stands, you're checking to see if the response is yes/no, starting a while loop which runs if it isn't yes/no, breaking the while loop prematurely, and then returning false on one of the conditions which spawned the while loop in the first place (read: not 'yes'), which finally gets handled as a 'no' (which may not be the case).
Try something like the following, if you want to use if-else:
public void askQuestion(){
String response = readline("Do you want to go to a movie tonight?");
getYesNoResponse(response);
}
public void getYesNoResponse(String answer){
if (answer.equals("yes"){
//print the yes response
} else if (answer.equals("no") {
//print the no response
} else {
askQuestion();
}
}

Java Try and catch

I have a java program that is supposed to handle an Exception, but the end result is far from what I intended it to be. Here is the overall idea of my program: it is supposed accept an input of zero and exit the program. The input dialog should cause an Exception which should be caught and print the message "bad number".
My brain is telling me I'm missing one line of code in the catch block.
here is my code:
import javax.swing.JOptionPane;
public class exceptTest {
public static void main(String[] args){
try {
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0"));
System.exit(0);
}catch(Exception e){
JOptionPane.showMessageDialog(null, "bad number");
}
}
}
You are not catching an exception here, you are simply making a if statement, you can just use an if/else.
try{
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0")){
System.exit(0);
}else{
JOptionPane.showMessageDialog(null, "bad number");
}
}catch (Exception ex){
ex.printStackTrace();
}
The catch you would only use for any exceptions showInputDialog() throws, but for your number check you are not catching anything, it just simply is not 0.
You don't execute your exception handling code because you never throw an exception. The code will execute the input, then test the input to be equal to "0", then based on that will or will not display a dialog, and then it will execute.
The throwing of an exception occurs either because something has happened outside the conditions that the code will handle, or because you throw one explicitly.
By "outside the conditions" etc., I mean something like dividing by 0. Java (nor any other language) will handle that, and an exception will be thrown. The normal steps of procedural processing will stop, and an execution handler will be called.
In your case, if you (for instance) attempted to parse the input to be a number, but the input was not a number, you would get an exception. This is different functionality than you say you wanted, but is a better illustration of what an exception is for. Something like
try
{
int numberEntered = Integer.parse(line);
JOptionPane.showMessageDialog(null, "Entered a number, parsed to " + numberEntered);
}
catch (NumberFormatException nfe)
{
JOptionPane.showMessageDialog(null, "Did not enter a number, but <" + line + ">");
}
shows the sort of thing exceptions are normally good for.
If you wanted to, you could define an exception, call it BadNumberException, and throw it in the code you have -- you would put it (I guess) in an else clause for your if statement. But your routine would be throwing the exception, and I think it is unusual for the routine that throws an exception to also catch it.
Hope that helps.
rc
You have a semi-colon after your if statement, it terminates the line and the compiler does not look for the rest of the if. Remove your semi-colon and it will work fine.
import javax.swing.JOptionPane;
public class exceptTest
{
public static void main(String[] args){
try
{
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0")) //semi-colon removed here
{
System.exit(0);
}
throw new IllegalArgumentException("Input was not 0");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "bad number");
}
}
}
Your code does not throw an exception if the input is not equal to 0. Therefore, you never catch anything, thus no errormessage is shown on the screen.
You could do two things:
- throw an exception if the input is not 0 (then you will enter the catch)
or
- use an else with your if that displays the error message (then you don't need the try-catch for checking whether the input is 0)
Edit: And of course as Hunter McMillen noticed, you need to remove the semicolon after your if statement.

Categories

Resources