When working with console command lines in java I found myself needing a solution that works when in certain situations. The console was a java based game and the need was user input because the game was being built in a text style format.
In this article I will be using ‘equalsIgnoreCase();’ to match a string with what I would like it to be. I will also be using the ‘Scanner’ class, keyboard inputs, and String objects. Here is the code that I will be working with…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import java.util.Scanner; public class userInputWithMenus { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.println("1. Menu."); System.out.println("2. Item."); System.out.println("3. Close.\n"); String inp = keyboard.nextLine(); if(inp.equalsIgnoreCase("1") || inp.equalsIgnoreCase("main")){ //execute what happens on main. }else if(inp.equalsIgnoreCase("2") || inp.equalsIgnoreCase("item")){ //execute what happens on item }else if(inp.equalsIgnoreCase("3") || inp.equalsIgnoreCase("exit")){ //execute what happens on close } } } |
The first thing we do is import a class that is built into java. Here we can access the scanner and assign a variable to it. Once we have our main class and main method setup we will display our menu and request the next line of text from the user and load this into the string ‘inp.’ The next block of code is the If else statements normally you would execute another method or run the program from this point on however that was not what I intended on covering here.
Inside of the if else blocks..
1 2 3 | if(){ } |
I placed code that matched the string contents with what I needed it to; in this case the menu items. I didn’t want the user to be forced into typing menu, item or exit so I made an or statement using ‘||’ to introduce the option of matching the string with the numbers. This is all done with a line that looks as follows.
1 | inp.equalsIgnoreCase("main") || inp.equalsIgnoreCase("1"); |
You can just use ‘imp.equals();’ however I in creating this some copying and pasting was done. To get your menu to work even better you can try putting it into a loop and breaking the loop when the user enters a valid command. This can be easily done with a boolean and a while loop.

