【问题标题】:Ask word that contains a letters contained in a array询问包含数组中包含的字母的单词
【发布时间】:2014-01-17 21:48:14
【问题描述】:

我有问题。我想让我的程序问我插入一个单词,这个单词的字母必须包含在一个数组中。

暂时,我想如果字母包含在数组中,打印(“字母正确”),否则打印(“字母不正确”)。

但总是返回(“字母不正确”),为什么?

请帮帮我!

公共类实用程序{

Scanner ent = new Scanner(System.in);
String insertedLetter = "";
String letters[] = {"a", "b", "c", "d", "e", "f", "g", "i", "j", "l", "m", "n", "o", "p", "r"};
String saveLetter = "";

public void askLetter() {
    for (int i = 0; i < letters.length; i++) {
        saveLetter += " " + letters[i] + ",";
    }
    System.out.println("Insert a word that contains these letters " + saveLetter);
    insertedLetter = ent.nextLine();

    if (saveLetter.equals(insertedLetter)) {
        System.out.println("The letter is correct");
    } else {
        System.out.println("The letter is incorrect");
    }
}

}

【问题讨论】:

  • 您认为equals 方法的作用是什么?只有当输入为" a, b, c, d, e, f, g, i, j, l, m, n, o, p, r," 时,您的程序才会正确输出。我不确定这就是你要找的东西。
  • 只有一个输入可以匹配您的saveLetter - 即插入一个包含这些字母 a、b、c、d、e、f、g、i、 j、l、m、n、o、p、r、a、b、c、d、e、f、g、i、j、l、m、n、o、p、r,字母正确“a , b, c, d, e, f, g, i, j, l, m, n, o, p, r,"...你需要尝试一个“包含”的方法。
  • insertedLetter.matches( "[a-r]+" ) 在做什么?不确定您是否接受空字符串 - 这将在单独的检查中完成。
  • 我要插入“f”,返回“单词正确”,因为数组中包含字母“f”。

标签: java arrays


【解决方案1】:

执行此操作的简单方法如下所示:

    boolean contained = true;
    for (int i = 0; i < insertedLetter.length(); i++) {
        if (saveLetter.indexOf(insertedLetter.charAt(i)) == -1) {
            contained = false;
            break;
        }
    }
    if (contained) {
        System.out.println("The letters are all contained in the saveLetter array");
    } else {
        System.out.println("One or more of the input letters are not contained in the saveLetter array");
    }

【讨论】:

  • 我的印象是他想逐个字母打印,不过你的代码很容易适应这个。
  • 哦!非常感谢!这是我想要的吗!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-30
  • 2015-08-16
  • 2017-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多