Jessica Hansen
Jessica Hansen

Reputation: 1

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

Upvotes: 0

Views: 247

Answers (3)

Jiajie Xu
Jiajie Xu

Reputation: 41

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

Upvotes: 1

Bruce Lin
Bruce Lin

Reputation: 76

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

Upvotes: 2

newToScala
newToScala

Reputation: 407

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

Upvotes: 0

Related Questions