![](/img/trans.png)
[英]How do you check if a number is in a list with Java (no given parameters)
[英]How do you check if a given sentence is avoiding a certain letter in java?
我一直在試圖弄清楚如何查看給定的句子是否是避免使用字母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! ");
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! ");
如果要比較某項,則應使用雙等於==
要搜索字符串中是否包含字符,可以使用contains方法;要檢查字符串中是否不包含字母,可以使用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!");
}
}
無需在這里重新發明輪子。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.