【问题标题】:If statement for checking if a char array contains a user given letter in Java用于检查 char 数组是否包含 Java 中用户给定字母的 if 语句
【发布时间】:2015-07-19 20:16:46
【问题描述】:

我正在尝试创建一个程序,其中用户输入一个字符串(放入一个 char 数组),然后输入一个字母,程序检查字符串是否包含该字母。到目前为止,这是我的代码:

Scanner keyboard = new Scanner (System.in);
System.out.println("Please enter a word: ");
String input = keyboard.nextLine();
char[] word = input.toCharArray();

Scanner keyboard1 = new Scanner (System.in);
char letter = keyboard1.findInLine(".").charAt(0);
if (word contains letter) { //This is just used as an example of what I want it to do
    System.out.println("The word does contain the letter.");
} else {
    System.out.println("The word does not contain the letter.");
}

我意识到 if 语句中的条件无效,我将其用作我希望它执行的示例。

所以我的问题是:我可以在 if 语句条件中输入什么来检查用户输入的单词是否包含用户输入的字母?

【问题讨论】:

标签: java arrays string if-statement char


【解决方案1】:

如果你想要它在一行上:

if (new String(word).indexOf(letter) != -1)

否则使用循环:

boolean found = false;
for (char c : word) {
    if (c == letter) {
        found = true;
        break;
    }
}

if (found)

【讨论】:

    【解决方案2】:

    您无需将第一个输入转换为char[],只需将其保留为字符串并使用contains()

    public static void main(String args[]) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Please enter a word: ");
        String input = keyboard.nextLine();
    
        System.out.print("Please enter a letter to search in the word: ");
        Scanner keyboard1 = new Scanner(System.in);
        char letter = keyboard1.nextLine().charAt(0);
    
        // Using toLowerCase() to ignore capital vs lowercase letters.
        // Locale may need to be considered.
        if (input.toLowerCase().contains(String.valueOf(letter).toLowerCase())) { 
            System.out.println("The word does contain the letter " + letter + ".");
        } else {
            System.out.println("The word does not contain the letter " + letter + ".");
        }
    }
    

    结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-21
      • 1970-01-01
      • 1970-01-01
      • 2016-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多