Take the 2-minute tour ×

I am wondering how to print a particular sentence depending on user input.

In the scenario below, if the user enters "B" I would like to print the words "You have selected B" however if the user selects C I would like to print the word "You have selected C".

import java.util.Scanner;
public class Trial extends Register

    //I want to load the register which will be option B

    public static void main (String[] args)
        Scanner input = new Scanner(System.in);
        System.out.println("Enter A to make a purchase & receive your change");
        System.out.println("Enter B to load the Register");
        System.out.println("Enter C to write the contents of the Register to a 
        web Page");
        System.out.println("Enter D to exit the program"); 
share|improve this question

2 Answers 2

up vote 0 down vote accepted

If you are using Java 7+, you can use a switch statement.

If you use an earlier vrsion, you need to use several if statements.

As for the Scanner, you can read this tutorial to get started and have a look at this example.

share|improve this answer

How about:

String input = // read input from scanner;
if(input.length() == 1) {
    switch(input.charAt(0)) {
    case 'A':
        // make purchase
    case 'B':
            // load register
    // Similarly case C and D
            // possibly invalid input as well

} else {
    System.out.println("Invalid input");
share|improve this answer

Your Answer


