你如何检查给定的句子是否避免了java中的某个字母?

时间:2016-10-14 23:22:02

标签: java boolean

我一直在试图弄清楚如何查看给定的句子是否是一个避免字母E的唇形图。我已经达到了我输入真/假陈述的程度,但它只输出“这句话是不是避免字母e的唇形图。“每次,输入是否包含e。我做错了什么?

boolean avoidsE = false, hasE = true, avoidsS = false, containsS = true;

for(int i = 0; i < sentence.length(); i++)
{
  if (sentence.charAt(i) == 'e')
  hasE = true;
  else
  avoidsE = false;
}

if (hasE = true)
System.out.println("This sentence is not a Lipogram avoiding the letter e. ");
else if (avoidsE = false)
System.out.println("This sentence is a Lipogram avoiding the letter e! ");

3 个答案:

答案 0 :(得分:2)

if (hasE == true) // "=" is to assign, you want to use "==" here to check  
    System.out.println("This sentence is not a Lipogram avoiding the letter e. "); 
else if (avoidsE == false) //same here   
    System.out.println("This sentence is a Lipogram avoiding the letter e! ");

答案 1 :(得分:1)

如果你想比较一些东西,你应该使用double equals ==

如果搜索字符是否在字符串中,您可以使用包含方法,并检查字符串中是否包含字母,您可以使用 indexOf 。它会是这样的:

public static void main(String[] args) {
    String sentence = "This is your sentence";

    if(sentence.contains("e")){
        System.out.println("This sentence is not a Lipogram avoiding the letter e. ");
    }
    else if("e".indexOf(sentence) < 0){
        System.out.println("This sentence is a Lipogram avoiding the letter e!");
    }
}

答案 2 :(得分:0)

无需在这里重新发明轮子。

public class Main {
    public static void main(String[] args) {
        System.out.println(hasChar("asdfe", 'e'));
        System.out.println(hasChar("asdfghij", 'e'));
    }

    static boolean hasChar(String str, char c) {
        return str.chars().anyMatch(x -> x == c);
    }
}

输出:

true
false