If-else条件语句在java中不能正常工作
我实际上实现了一个简单的程序。但是下面的代码段并没有按照我想要的那样工作If-else条件语句在java中不能正常工作,java,Java,我实际上实现了一个简单的程序。但是下面的代码段并没有按照我想要的那样工作 if((charAtIndexTwo !='A') || (charAtIndexTwo !='E') || (charAtIndexTwo !='I') || (charAtIndexTwo !='O') || (charAtIndexTwo !='U') || (charAtIndexTwo !='Y')) { System.out.println((charAtIndexTwo!='A'));
if((charAtIndexTwo !='A') || (charAtIndexTwo !='E') || (charAtIndexTwo !='I') || (charAtIndexTwo !='O') || (charAtIndexTwo !='U') || (charAtIndexTwo !='Y')) {
System.out.println((charAtIndexTwo!='A'));
if((totalOne%2 ==0) && (totalTwo%2==0) && (totalThree%2==0) && (totalFour%2==0)) {
System.out.println("Valid");
}
else {
System.out.println("invalid");
}
}
else{
System.out.println("Invalid");
}
如果我使用
charAtIndexTwo=A
运行程序,控制台将打印false。这不可能发生。我想,因为在第一个if段中,我检查charAtIndexTwo
是否等于A。因为它是一个,程序如何打印false而不是跳转到else段?有人能告诉我为什么吗?问题在于你的OR(| |)状况。
(charAtIndexTwo!='A')|(charAtIndexTwo!='E'))
现在第一部分肯定是false,它应该跳转到else,但是OR(| |)条件使它检查(charAtIndexTwo!=“E”)是否为TRUE。因此,它没有转到else,而是进入if条件并打印FALSE(其本身是正确的)
您只需要调整IF条件逻辑
if((charAtIndexTwo=='A')||(charAtIndexTwo=='E')||(charAtIndexTwo=='I')||(charAtIndexTwo=='O')||(charAtIndexTwo=='U')||(charAtIndexTwo=='Y'))
{
System.out.println("Invalid");
}else
{
System.out.println((charAtIndexTwo != 'A'));
if ((totalOne % 2 == 0) && (totalTwo % 2 == 0) && (totalThree % 2 == 0) && (totalFour % 2 == 0)) {
System.out.println("Valid");
} else {
System.out.println("invalid");
}
}
在这一行中,您使用或条件进行计算,这意味着如果任何一个条件为真,那么程序将跳转到if
当charAtIndexTwo=A时,则
(charAtIndexTwo !='A') = False || (charAtIndexTwo !='E') = True
// this is where it enters the If Condition
解决方案:将所有或| |替换为和&您的第一个条件始终为真。。您是否打算使用
&&
?第一个条件没有用处charAtIndexTwo
不能同时具有多个值,因此必须至少有一个选项为true,才能使整体条件为true。如果charAtIndexTwo=='A'
,则我希望您的第一个println()
语句将false
输出到控制台。不是吗?不。如果charAtIndexTwo='A'如何实现第一个println()@user7如果charAtIndexTwo='A'如何实现第一个条件?这意味着我必须用&&ryt替换| |?很可能是的。我不能确定你的要求。谢谢。我理解这里的概念。
(charAtIndexTwo !='A') = False || (charAtIndexTwo !='E') = True
// this is where it enters the If Condition