Question

When I input any valid option (A,B,C) the if statement thinks that option is anything but A, B, or C, and will lead into a continuous loop.

package other;

import java.util.Scanner;

public class Menu implements InterfaceMenu{

private String option;

public void greeting(){

    System.out.println("This program will use the Pythagorean Theorem");
    System.out.println("to calculate a missing side.\n");
    System.out.println("Choose an option!\n");
    System.out.println("Choose Option A for missing side c");
    System.out.println("Choose Option B for missing side b");
    System.out.println("Choose Option C for missing side a\n");

}

public String optionGet(){

    System.out.print("Choose an option: ");
    Scanner ad = new Scanner(System.in);
    option=ad.next().toUpperCase();

    if( (option=="A") || (option=="B") || (option=="C") ){
        ad.close();
    }
    else{
        optionGet();
    }

    return option;
}

}
Was it helpful?

Solution

Aside from using the wrong method to compare strings, there is another serious problem: optionGet() opens a new Scanner on system.in. If the input contains an option that is not A, B, or C, then optionGet() calls itself recursively. The recursive call does another

Scanner ad = new Scanner(System.in);

while the first one is still open. There is no telling just what that will do, but it is likely to cause problems. Do not do that. Don't use recursion. It's inappropriate here. Instead, put the code that checks for options in a loop, and make sure new Scanner is outside the loop.

OTHER TIPS

use option.equalsIgnoreCase("A") instead of ==. because == compares the reference variables and equals compars the content .

In Java strings cannot be compared using the == identifier in the same way as you would for integers. Instead you can use String.equals().

For what you have written however it may be best to compare characters however that will require changing the returned variable type within optionGet() to public char optionGet(). Doing this however will also require you to change the type of option to char. Changing the type to char will allow you to compare characters using ==.

Also be sure to define Scanner ad outside of optionGet() as your current code is redefining it for every reiteration.

Your call as to what you think is easier.

Use the the String.equals() method. Not the == comparator. Whereas .equals() checks for equality between strings, == checks if their references are the same, which isn't what you want to do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top