【问题标题】:Printing different sentences depending on user input根据用户输入打印不同的句子
【发布时间】:2012-07-20 20:39:33
【问题描述】:

我想知道如何根据用户输入打印特定的句子。

在下面的场景中,如果用户输入“B”,我想打印“You have selected B”,但是如果用户选择 CI,我想打印“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"); 
 }    

【问题讨论】:

    标签: java printing if-statement input


    【解决方案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");
    }
    

    【讨论】:

      【解决方案2】:

      如果您使用的是 Java 7+,则可以使用 switch statement

      如果使用较早的vrsion,则需要使用多个if statements

      至于扫描仪,您可以阅读this tutorial 以开始使用并查看this example

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-05
        • 2023-02-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-03
        相关资源
        最近更新 更多