如何让用户选择是否

时间:2014-02-08 01:34:03

标签: java input output

这是我的代码。我知道,这很简单,就在本课程的第4周左右。

    System.out.print("What is your first name? ");

    String first = in.next();

    System.out.print("What is your middle name (If not, just type the RETURN key)?                                      ");

    String middle = in.next();

    System.out.print("What is your last name? ");

    String last = in.next();

    int flength = first.length();

    int mlength = middle.length();

    int llength = last.length();

    int tlength = flength + mlength + llength;

    System.out.println("The total number of characters is: " + tlength);

我希望能够允许用户选择是否添加中间名,但目前我的代码要求他们输入中间名。有没有办法解决这个问题而不使用if语句? (我不允许使用它)

1 个答案:

答案 0 :(得分:0)

我假设因为你不能使用“if”语句,那么你也不能在输入上使用开关,因为这在技术上是一个更高级的概念...但如果可以,也许你可以尝试这样的事情。

询问用户是否要输入中间名,并要求输入“Y”或“N”,并将其存储在字符(char)变量中以表示是或否。

然后,尝试这样的事情:

switch(charVariable) {
    case 'N': //continue to last name, set middle name to "" or something.
                 break;
    case 'Y': //ask for middle name
                 break;
    default: //this will happen if anything besides "Y" or "N" is input. Maybe assume "no"?

如果没有“if”声明,我真的不确定如何做到这一点。