有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何让扫描仪从用户输入中选择关键字?

如果用户输入的是“it's cold outside”,而不仅仅是“cold”,那么程序会移动(就像它应该做的那样)到else语句。我如何让它在不知道用户输入的情况下运行并选择关键字

   System.out.println("I am doing well, thank you!  How's the weather today?");
    String s = scan.nextLine();
        if (s.equalsIgnoreCase("cold") || s.equalsIgnoreCase("freezing")) {
            System.out.println("You'd better bundle up");                
        } else {
           System.out.println("Stay cool");
        }   

共 (3) 个答案

  1. # 1 楼答案

    试试看:

    if (s.contains("cold") || s.contains("freezing"))
    

    这里contains()方法搜索字符串中的字符序列。如果找到字符值序列,则返回true

    注意:equalsIgnoreCase方法根据字符串的内容比较两个字符串,而不考虑大小写

  2. # 2 楼答案

    您需要使用contains和toLowerCase。例如:

      System.out.println("I am doing well, thank you!  How's the weather today?");
        String s = scan.nextLine();
            if (s.toLowerCase().contains("cold") ||  s.toLowerCase().contains("freezing")) {
                System.out.println("You'd better bundle up");                
            } else {
               System.out.println("Stay cool");
            }   
    
  3. # 3 楼答案

    您可以使用^{}检查输入中是否有关键字,如下所示:

    Scanner scan = new Scanner(System.in);
    System.out.println("I am doing well, thank you!  How's the weather today?");
    String s = scan.nextLine();
    if (s.indexOf("cold")>-1 || s.indexOf("freezing")>-1) {
         System.out.println("You'd better bundle up");                
    } else {
         System.out.println("Stay cool");
    }