Search code examples
javaunreachable-code

Unreachable code when closing scanner in java?


When I try to close myScanner I get a red line under myScanner.close telling me it is unreachable code. What am I doing wrong?

public class crypt {    

static final char FIRST = ' ';
static final char LAST = ']';

static final int RANGE = LAST-FIRST+1;

public static void main(String[] args) {
    safe("");

}

public static boolean safe(String word) {
    Scanner myScanner = new Scanner(System.in);
    word = myScanner.nextLine();
    String upper = word.toUpperCase();
        for (int i=0; i<upper.length(); i++) {
            char c = upper.charAt(i);
                if (c < FIRST && c > LAST) {
                    return true;
                }
        }
    return false;
    myScanner.close();
} 

Solution

  • You'll want to move myScanner.close(); to the line before 'return false;'. Another thing to note - you aren't closing the scanner when you return true. You may want to add myScanner.close(); in front of return true;.

    public static boolean safeToUse(String plaintext) {
        Scanner myScanner = new Scanner(System.in);
        plaintext = myScanner.nextLine();
        String upper = plaintext.toUpperCase();
            for (int i=0; i<upper.length(); i++) {
                char c = upper.charAt(i);
                    if (c < FIRST && c > LAST) {
                        myScanner.close(); //Close the scanner before you return true
                        return true;
                    }
            }
        myScanner.close(); //close the scanner before you return.
        return false;
    } 
    

    When you are inside a function, code will not be executed after you return. Think of return as marking a stopping point in your code. When it reaches this point it will go to where that method/function(safeToUse() in your case) was called.

    A good way of tracking and better understanding the execution of the code it to step through your program, although you'll have to make the suggested changes first to get it to compile.