0

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"); 
 }    
assylias
  • 297,541
  • 71
  • 621
  • 741
Kerry G
  • 863
  • 4
  • 12
  • 21

2 Answers2

1

How about:

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

    }
} else {
    System.out.println("Invalid input");
}
Jeshurun
  • 21,639
  • 5
  • 75
  • 88
0

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.

Community
  • 1
  • 1
assylias
  • 297,541
  • 71
  • 621
  • 741