简体   繁体   English

您如何检查给定的句子在Java中是否回避某个字母?

[英]How do you check if a given sentence is avoiding a certain letter in java?

I have been trying to figure out how to see if a given sentence is a lipogram avoiding the letter E. I have gotten to the point where I put in the true/false statements, but it is only outputting "This sentence is not a Lipogram avoiding the letter e. " every time, whether the input contains e or not. 我一直在试图弄清楚如何查看给定的句子是否是避免使用字母E的口形图。我已经达到了输入真假陈述的地步,但是只输出了“此句子不是口形图”每次输入是否包含e时都应避免使用字母e。“。 What am I doing wrong? 我究竟做错了什么?

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! ");
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! ");

If you want to compare something you should use double equals == 如果要比较某项,则应使用双等于==

For search if an character is in the string you can use contains method and to check if letter is not contained in the string you can use indexOf . 要搜索字符串中是否包含字符,可以使用contains方法;要检查字符串中是否不包含字母,可以使用indexOf It would be something like this: 就像这样:

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!");
    }
}

No need to reinvent the wheel here. 无需在这里重新发明轮子。

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);
    }
}

Output: 输出:

true
false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM