条件语句在 if-else-if 阶梯的两个部分都为真

Conditional statement true in both parts of if-else-if ladder(条件语句在 if-else-if 阶梯的两个部分都为真)

本文介绍了条件语句在 if-else-if 阶梯的两个部分都为真的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你有这样的代码:

if (A > X && B > Y)
{
   Action1();
}
else if(A > X || B > Y)
{
   Action2();
}

使用 A >XB >Yif-else-if 梯形图的两个部分都会执行吗?

With A > X and B > Y, will both parts of the if-else-if ladder be executed?

我正在处理存在这种情况的 Java 代码.我通常使用 C++ 工作,但我是一个非常新的(和零星的)两种语言的程序员.

I'm dealing with Java code where this is present. I normally work in C++, but am an extremely new (and sporadic) programmer in both languages.

推荐答案

不,它们不会同时执行.它按照您编写它们的顺序排列,从逻辑上讲这是有道理的;即使第二个读作else if",您仍然可以将其视为else".

No, they won't both execute. It goes in order of how you've written them, and logically this makes sense; Even though the second one reads 'else if', you can still think of it as 'else'.

考虑一个典型的 if/else 块:

Consider a typical if/else block:

if(true){
   // Blah
} else{
   // Blah blah
}

如果您的第一个陈述是正确的,那么您甚至不必费心查看在 else 情况下需要做什么,因为它是无关紧要的.同样,如果你有'if/elseif',你就不会浪费时间查看后续的块,因为第一个是真的.

If your first statement is true, you don't even bother looking at what needs to be done in the else case, because it is irrelevant. Similarly, if you have 'if/elseif', you won't waste your time looking at succeeding blocks because the first one is true.

一个真实的例子可能是分配成绩.你可以试试这样的:

A real world example could be assigning grades. You might try something like this:

if(grade > 90){
   // Student gets A
} else if(grade > 80){
   // Student gets B
} else if(grade > 70){
   // Student gets c
}

如果学生得到了 99%,那么所有这些条件都是正确的.但是,您不会分配学生 A、B 和 C.

If the student got a 99%, all of these conditions are true. However, you're not going to assign the student A, B and C.

这就是为什么顺序很重要.如果我执行了这段代码,并将 B 块放在 A 块之前,那么您将为同一个学生分配 B 而不是 A,因为不会执行 A 块.

That's why order is important. If I executed this code, and put the B block before the A block, you would assign that same student with a B instead of an A, because the A block wouldn't be executed.

这篇关于条件语句在 if-else-if 阶梯的两个部分都为真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:条件语句在 if-else-if 阶梯的两个部分都为真

基础教程推荐