我正在编写一个程序,用于检查给定的句子是否为完全句,但我无法将每个字符与字符串中的字符进行比较。
有谁能建议我一种获取所需输出的方法吗?
Scanner scan = new Scanner(System.in);
String panagram = scan.nextLine();
String word = panagram.toLowerCase();
System.out.println(word);
String a[] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
"x", "y", "z" };
int count = 1;
System.out.println("a=" + a.length);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < word.length(); j++) {
if ((a[i]).equals(word.charAt(j)))// problem occurs here {
count++;
break;
}
}
}
if (count == 26) {
System.out.println("pangram");
} else {
System.out.println("not pangram");
}
char[]
代替String[]
。 - RealSkepticO(n)
,其中 n 为字符数)添加到集合中,然后检查 Set 的大小。请注意,检查是否正在添加的元素是 char 类型的 if 条件语句是O(1)
。 - TheLostMinda [0] =“a”
。现在,您循环遍历26个'a'字符的字符串,并在内部循环的每次迭代中调用count ++
。最终,count
将为26,而您的代码假定这是一个句母句(尽管它不是)。除此之外,它对于长度超过26个字符的字符串也无效。因此,最好使用TheLostMind建议的集合方法。 - ThomasString#equals
方法将始终返回false
,如果obj instanceof String == false
,其中obj
是word.charAt(j)
所表示的一个字符。由于obj
是一个Char
,您永远无法将一个String
与另一个不表示String
的Object
进行比较。 - SomeJavaGuyif ((a[i]).equals(word.charAt(j))
稍作修改为if ((a[i]).equals("" + word.charAt(j))
,即可实现字符串之间的相等性检查。 - Developer Marius Žilėnas