2012-07-22 34 views
0

我在想如何根據用戶輸入打印特定的句子。根據用戶輸入打印不同的句子

在下面的情況下,如果用戶輸入「B」,我想打印「您已經選擇B」字樣,但是如果用戶選擇C,我想打印單詞「您選擇了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"); 
}  

回答

1

如何:

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"); 
}