字符串与多个单词的比较

String Comparison with Multiple Words

如何在 if/then 语句中比较一个字符串和多个单词?我试过这个:

System.out.println("How would you describe your active lifestyle? Sedentary, Somewhat Active, or Active?");
        String lifestyle = sc.next();
        double activity;
        if(lifestyle.equalsIgnoreCase("sedentary"))
            {
                    activity = 0.2;
            }
        else if(lifestyle.equalsIgnoreCase("somewhat active"))
            {
                activity = 0.3;
            }
        else
            {
                activity = 0.5;
            }

但是当你输入"somewhat active"时,它会将变量activity赋值给0.5。我怎样才能让它注册 "somewhat active" 是一个东西?

Scanner 上的 next() 方法检索下一个标记,默认情况下是空格。 lifestyle 变量只包含 "somewhat".

将对 next() 的调用替换为对 nextLine() 的调用,这将获取该行的所有单词。

But when you enter "somewhat active", it assigns the variable activity to 0.5

因为在 "somewhat active"next() 只会检索 somewhat 作为令牌。 next() 方法只读到白色 space。默认分隔符是 space。您可以在您的案例中指定定界符 i.e . 并且它将读取标记直到输入中出现 . 或更好地使用 nextLine 方法。

Scanner sc = new Scanner(System.in);
sc.useDelimiter("\.");//provide input as somewhat active.

当您使用 sc.next()Scanner class 只读 "somewhat" 即(它只读到空格或空白)。

相反,当您使用 sc.nextLine() 时,Scanner class 会将完整的字符串读取为 "somewhat active"。

一般来说,如果你只想读一个单词,使用 next(); 方法。如果您想阅读一行(包括空格在内的多个单词),请使用 nextLine();