【问题标题】:String Comparison with Multiple Words与多个单词的字符串比较
【发布时间】:2015-09-09 18:13:04
【问题描述】:

如何在 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;
            }

但是当您输入“有点活跃”时,它会将变量活动分配为 0.5。我怎样才能让它注册“有点活跃”的东西?

【问题讨论】:

  • 另外,您应该寻找 Somewhat Active 或 Sedentary,而不是 Sedentary 或有点活跃。 (案例)更改后 sc.nextLine().

标签: java string if-statement comparison


【解决方案1】:

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

next() 的调用替换为nextLine() 的调用,这将使所有单词都在线。

【讨论】:

    【解决方案2】:

    但是当你输入“有点活跃”时,它会分配变量活动 为 0.5

    因为在"somewhat active" next() 只会检索somewhat 作为令牌。 next() 方法只能读取到空白区域。默认分隔符是space。您可以在您的情况下指定分隔符 .,它会读取令牌,直到输入中出现. 或更好地使用nextLine 方法。

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

    【讨论】:

      【解决方案3】:

      当您使用 sc.next() 时,Scanner 类只读取“有点”,即(它只读取直到空白或空白)。

      当您使用sc.nextLine() 时,Scanner 类会将完整的字符串读取为“有点活跃”。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-27
        • 1970-01-01
        • 2017-11-12
        • 2021-05-09
        • 2016-06-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多