if语句用于检查char数组是否包含Java中的用户给定字母

时间:2015-05-08 19:55:16

标签: java arrays string if-statement char

我正在尝试创建一个程序,其中用户输入一个字符串(放入一个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语句条件中输入什么来检查用户输入的单词是否包含用户输入的字母?

2 个答案:

答案 0 :(得分:5)

您无需将第一个输入转换为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 + ".");
    }
}

结果:

enter image description here

enter image description here

答案 1 :(得分:1)

如果你想要它在一行:

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

否则使用循环:

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

if (found)