1

First of all I am new to this site, but anyways, here is my problem. In my if then statement, I type in "Gen" and it works, but if I type "Launch nuke" or "launch nuke" or "Who am I?" it just ends up saying "Unknown Command" which means it doesn't match any of the statements (or whatever it's called). I tried using == as well but they both don't work. Of course I type Gen first and the Launch nuke after. Here is the code:

import java.util.Scanner;
public class testing {
    public static void main(String[] args) {

        String alpha;
        String bravo;
        String charlie;
        Scanner input = new Scanner(System.in);         
        System.out.print("Please confirm identity: ");
        alpha = input.next();

        if (alpha.equals("Gen")) {
            System.out.println("Hello General"); 
            System.out.println("Identity Confirmed");
            System.out.print("Please input command: "); 
            bravo = input.next();

            if (bravo.equals("Launch nuke")) {                          
                System.out.println("Launching Missiles"); 
            }   

            else if (bravo.equals("launch nuke")) {
                System.out.println("Launching Missiles");
            }

            else if (bravo.equals("Who am I?")) {
                System.out.print("You are the General");
            }   

            else
                System.out.print("Unknown Command");
        }

        else
            System.out.println("Access Denied");                    
    }
}
Scott
  • 1,706
  • 1
  • 20
  • 40
Lee
  • 41
  • 1
  • 8

3 Answers3

3

You are using input.next(). It will read only one complete word for eg: "Launchnuke". The next() method will split it to string[] with space.

So try using input.nextLine(), it should work.

Genhis
  • 1,353
  • 3
  • 22
  • 26
Naveen
  • 346
  • 2
  • 12
2

input.nextLine() instead of input.next() should fix it. Use it for both, alpha and bravo. input.next() only takes the next token into account (like "launch"), while your commands have more than one.

dly
  • 1,042
  • 1
  • 16
  • 21
-3

Oh I don't have enough reputation.. anyway. you should type Gen first and Launch nuke or any thing to do that because your Launch nuke if statement is inside Gen if statement