0

Below is my code. I have tried to use numbers as cases instead of letters and it worked. however i would like to use letters instead. this is where i get issues. Please help me . Thanks

public class Hello {
    public static void main(String[] args) throws IOException {

        String input = "input";
        Scanner scanner = new Scanner(System.in);
        switch (scanner.next()) {


        case "f" :
        case "F" :
        case "Forward" :
        case "forward" :

            while (input == "f");
            System.out.println("You Have Chosen Forward");
            System.out.println("Enter a speed and duration");

            else
                System.out.println("the values you have written are out of range");
            break;

    case "b" :
        case "B" :`enter code here`
        case "Backward" :
        case "backward" :

            while (input == "b");
            System.out.println("You Have Chosen backward");
            System.out.println("Enter a speed and duration");

            else
                System.out.println("the values you have written are out of range");
            break;

        case "Q":
            System.out.println("Goodbye!");
            System.exit(0);
        }

}

}

  • `while (input == "f");` would be an infinite loop, if `input` ever did `== "f"` (which it won't). – Elliott Frisch Feb 11 '20 at 17:15
  • @ElliottFrisch, we don't know that it won't. In some VMs the very aggressive optimizer can do that sort of thing. – M. Prokhorov Feb 11 '20 at 17:22
  • 1
    @M.Prokhorov `String input = "input";` - so it will never `== "f"`, and if it's read from a `Scanner` the input will be a new instance of `String`. – Elliott Frisch Feb 11 '20 at 17:26
  • @ElliottFrisch, oh, right. Missed that one. – M. Prokhorov Feb 11 '20 at 17:27
  • @ElliottFrisch when i run it, it isnt an infinte loop. it just does its function, then ends –  Feb 11 '20 at 17:36
  • None of your `while` loops do anything. Because they have empty bodies, if those loops were entered they would be infinite. Why are they there? Start over with what you **want**, if you want to "loop a switch statement" then the `switch` statement should be **in** a loop; why have you tried to put loop statements **in** a `switch`? – Elliott Frisch Feb 11 '20 at 17:49

0 Answers0