Many times, when you have complicated conditions, you want to combine them. For
example, maybe you want to do something if one condition is true, or another
one. In Java, there are three operators that you can use to combine conditions.
They look like this. The two ampersands are an and these two vertical bars are
on or. And the exclamation mark somewhat is a not. You might find it useful to
remember that the not equal operator that you've seen a few units ago also has
the exclamation mark. Let me show you a few examples for using these operators.
And once again, we'll be looking at flags where the visual appearance should
help you. Let's start with this maritime flag for the letter d. Here, I made a
sketch of this flag. When you're in the middle, the pixel should be blue. And
otherwise, it should be yellow. So how do we express when you're in the middle?
When the y-value is greater than this level. And less than this level, that's
where our and comes in, then we're in the middle. This here is 1 5th of the
total height. So, we have two conditions, namely y is at least height over 5,
and the other condition is y is at most height times 4 over 5. Both conditions
have to be fufilled for us to be in the middle, so we use the and operator.
Here it is. Let's just try this out. Here is the condition that you just saw
with the and operator here. And in this case, we return blue. Otherwise, we
return yellow. In this case, I will make a square flag and here it is. So, the
and operator worked out for us. Because we wanted y to be at least here at
most, here. Both conditions had to be true for the blue color. Now, let's look
at another flag. I've sketched up the flag here. And the question is, when
should a pixel be blue. In this case, there are four conditions. The x-value
should be at least width over third. That means it's over here. The x-value
should be at most, width times two thirds. That makes it over here. The y-value
should be the height over 3, and the y-value should be at most the height times
two third. All those four conditions need to be fulfilled for a pixel to be
built. Now, it's your turn. You'll get to write a program that draws this flag
here with a bit of blue on the inside and white on the outside.
Muchas veces, cuando tienes condiciones complicadas, buscas combinarlas. Por
ejemplo, tal vez quieres hacer algo si una condición es verdadera, u
otra. En Java, hay tres operadores que puedes utilizar para combinar condiciones.
Se ven así. Los dos símbolos de unión son un and (y), estas dos barras verticales son
un or (o), y el signo de exclamación, no muy intuitivo, es un no. Puede que te resulte útil
recordar que el operador no igual que viste hace unas unidades también tiene
el signo de exclamación. Te voy a enseñar algunos ejemplos de uso de estos operadores.
Y una vez más, vamos a estar buscando banderas cuyo aspecto visual debe
ayudarte. Vamos a empezar con esta bandera marítima para la letra D. Aquí, hice un
esbozo de esta bandera. Cuando estás en el medio, los píxeles deben ser de color azul, y
de lo contrario, deben ser de color amarillo. Entonces, ¿cómo expresamos cuando estás en el medio?
Cuando el valor de y es mayor que este nivel y menor que este nivel, aquí es
donde nuestro «and» entra, entonces estamos en el medio. Esto aquí es una 5ta parte de la
altura total. Así, tenemos dos condiciones, a saber, «y» es por lo menos la altura sobre 5,
y la otra condición es «y» es por lo mucho la altura por 4 sobre 5. Ambas condiciones
deben satisfacerse para que estemos en el medio, así que usamos el operador «and».
Aquí está. Vamos a probar esto. Esta es la condición que acabas de ver
con el operador «and» aquí. Y en este caso, devolvemos color azul. De otro modo,
devolvemos color amarillo. En este caso, voy a hacer una bandera cuadrada y aquí está. Entonces, el
operador «and» funcionó para nosotros porque queríamos que «y» estuviera por lo menos aquí, cuando
mucho, aquí. Ambas condiciones tuvieron que ser verdad para el color azul. Veamos ahora
otra bandera. He esbozado la bandera aquí. Y la pregunta es, ¿cuándo
un píxel debe ser color azul? En este caso, hay cuatro condiciones. El valor de x
debería ser al menos anchura sobre un tercio. Eso significa que está por aquí. El valor de x
debe ser cuando mucho, la anchura por dos tercios. Estaría por aquí entonces. El valor de y
debe ser cuando menos la altura sobre 3, y el valor de y debe ser cuando mucho la altura por
dos tercios. Todas esas cuatro condiciones deben cumplirse para que un píxel sea
de color azul. Ahora es tu turno. Tendrás la oportunidad de escribir un programa que dibuja esta bandera de
aquí con un poco de azul en el interior y el blanco en el exterior.
Souvent, quand vous avez
des conditions compliquées,
vous voulez les combiner.
Vous voulez peut-être faire quelque chose
si une condition est vraie ou une autre.
Dans Java, vous pouvez combiner
des conditions à l'aide de trois opérateurs.
Ils ressemblent à ceci.
Les deux ampères sont un and,
ces deux barres verticales sont un or
et le point d'exclamation est,
contre-intuitivement, un not.
Ce serait sans doute utile de
se rappeler que l'opérateur !=
que vous avez vu il y a quelques unités
a aussi le point d'exclamation.
Je vais vous montrer quelques exemples
d'utilisation de ces opérateurs.
Là encore, nous regarderons des drapeaux
où l'apparence visuelle devrait aider.
Commençons par ce drapeau
maritime pour la lettre d.
Ici, j'ai fait un croquis
de ce drapeau.
Lorsque vous êtes au milieu,
le pixel doit être bleu
et sinon, il devrait être jaune.
Comment peut-on exprimer
quand on est au milieu?
Lorsque la valeur y est
supérieure à ce niveau
et inférieur à celui-là, c'est là où vient
notre and, alors nous sommes au milieu.
Celui-ci est 1/5 de la hauteur totale.
Nous avons deux conditions, à savoir
y est au moins height / 5,
et l'autre condition est
y est au plus height * 4 / 5.
Ces deux conditions doivent être remplies
pour que nous soyons au milieu,
donc nous utilisons l'opérateur and.
Le voici.
Essayons cela.
Voici la condition que vous venez
de voir avec l'opérateur and.
Et dans ce cas, nous renvoyons bleu,
sinon, nous renvoyons jaune.
Dans ce cas, je ferai
un drapeau carré et voilà.
L'opérateur and
a travaillé pour nous
car nous voulions que y
soit au moins ici, au plus, ici.
Les deux conditions devaient être
vraies pour la couleur bleue.
Regardons un autre drapeau.
J'ai dessiné le drapeau ici
et la question est, quand
un pixel devrait-il être bleu?
Dans ce cas, il y a quatre conditions.
La valeur x doit être au moins
égale à la largeur du tiers.
Ça signifie que
c'est fini ici.
La valeur x doit être au maximum,
largeur fois deux tiers.
Ce qui l'amène ici.
La valeur y doit être
la hauteur supérieure à 3
et la valeur y doit être au plus
la hauteur fois deux tiers.
Ces quatre conditions doivent être
remplies pour qu'un pixel soit construit.
Maintenant c'est à vous.
Vous aurez à écrire un programme
qui dessine ce drapeau
avec un peu de bleu à l'intérieur
et blanc à l'extérieur.
複雑な条件が出てくると
それらを結合したくなります
例えば真の条件と偽の条件がある場合です
Javaでは条件を結合する際に使用できる演算子が
3つあります
&&はand、||はor、
!はnotです 以前学んだ!=演算子にも
!が入っていたことを覚えておくと役に立ちます
これらの演算子を使った例題を
いくつかお見せします
形が分かりやすいので再び旗を見てみましょう
文字Dを示すこの国際信号旗から始めます
まず旗をスケッチしました
真ん中ではピクセルは青になります
それ以外は黄色です
真ん中の部分をどう表しますか?
yの値がここより下にありここより上にある場合
真ん中の部分だと言えます
ここの長さは高さ✕1/5
2つの条件がありますね
y>=height/5とy<height✕4/5です
真ん中にいるには両方の条件を
満たす必要があります
ここに&&を使います さあやってみましょう
さっきの&&を含んだ条件がここにあります
この場合青を返します
それ以外は黄色です
このように四角い旗を作ります
ここで&演算子が役に立ちます
少なくとも2ヵ所にyが欲しいからです
青にするには両方の条件が真である必要があります
他の旗のスケッチをここに書きました 問題は
どんな時にピクセルが青になるかです
この場合4つの条件があります
xの値は最小で幅✕1/3です
ここから右ということですね
xの値は最大で幅✕2/3となります
yの値は高さ✕1/3より大きく
高さ✕2/3より小さくなります
ピクセルを青にするには
4つの条件すべてを満たす必要があります
次は皆さんの番です
外側は白で内側が青の旗を描くための
プログラムを書きましょう
조건을 만들 때, 때로는 굉장히 복잡한 조건을 만들어야할 때가 있습니다.
예를 들어서, 한 조건 안에 두 개의 조건을 넣을 수도 있습니다.
자바에서는 조건을 합칠 수 있게 해주는 연산자가 세 개 있습니다.
이렇게 생겼습니다. &&는 AND이고, ||는 OR이고,
!는 NOT입니다. NOT(!)은 지금까지 가끔 나와서
기억하기 쉬울 겁니다.
이 논리 연산자들을 이용하는 예를 몇 가지 보여드리겠습니다.
다시 한 번 국기를 이용해서 연산자들을 이용하겠습니다.
철자 d를 이용한 Maritime 국기를 이용합시다. 여기에 제가
국기를 스케치 했습니다. 가운데에 있으면 픽셀은 파란색이여야 합니다.
그리고 나머지는 모두 노란색이여야 합니다. 가운데에 있다는 걸
어떻게 표현해야 할까요? y좌표가 이 레벨보다 높고 이 레벨보다
낮으면, 가운데가 됩니다. 이 부분은 전체 높이의 1/5입니다.
그래서 두 개의 조건이 있습니다. y >= height / 5,
y < height * 4 / 5입니다. 두 조건 모두가 참이 여야
가운데에 있는 걸로 됩니다. 이를 위해 AND 연산자를
사용합니다. 한 번 실행해 봅시다. 이 조건식은 방금 여러분이
본 조건식입니다. 이 조건이 참이 되면 파란색을 리턴 합니다.
이 외의 경우에는 노란색을 리턴 합니다. 사각형의 국기로 만들어서
실행해 보니 좋은 결과가 나왔습니다. 왜냐하면 y의 위치에 대한
조건을 잘 잡았기 때문입니다. 두 조건 모두 참이 되어야 blue가 실행 됩니다.
이제 다른 국기를 그려 봅시다. 이 국기를 여기에 스케치해뒀습니다.
픽셀이 어떨 때 파란색이여야 할까요? 이번 국기는 4개의 경우가
있습니다. x값이 최소로 1/3은 넘어야 한다는 것이고, 최대로는
2/3입니다. 그렇다면 여기까지 입니다. y 값은
높이의 1/3이고 높이의 2/3까지만 파란색이 되어야 합니다.
이 네 개의 조건이 모두 충족된다면, 파란색으로
색칠이 됩니다. 이제 여러분께서 프로그램을 작성할 차례입니다.
이 국기를 그려보길 바랍니다.