Java двойной тернарный оператор

can you have two conditions in an if statement

I’m a beginner in coding. I was recently working with to create a chatting programme where a user will chat with my computer. Here is a part of the code:

System.out.println("Hello, what's our name? My name is " + answer4); String a = scanner1.nextLine(); System.out.println("Ok, Hello, " + a + ", how was your day, good or bad?"); String b = scanner2.nextLine(); **if (b.equals("good"))** < //1 System.out.println("Thank goodness"); >else **if (b.equals("it was good"))** < //2 System.out.println("Thank goodness"); >else **if (b.equals("bad"))** < //3 System.out.println("Why was it bad?"); String c = scanner3.nextLine(); System.out.println("Don't worry, everything will be ok, ok?"); String d= scanner10.nextLine(); >else **if (b.equals("it was bad"))** < //4 System.out.println("Why was it bad?"); String c = scanner3.nextLine(); System.out.println("Don't worry, everything will be ok, ok?"); String d= scanner10.nextLine(); >if(age <18)else if (age>=18)

The conditions of the if statements are in Bold (surrounded with ** ). In case of first and the second condition I want my application to do same thing. Similarly third and fourth condition. I thought it was possible to somehow group them in if statement. I tried with below code but it doesn’t compile:

if (b.equals("good"), b.equals("it was good")) < System.out.println("Thank goodness"); >else if (b.equals("bad"),(b.equals("it was bad")))

6 Answers 6

You can use logical operators to combine your boolean expressions .

  • && is a logical and (both conditions need to be true )
  • || is a logical or (at least one condition needs to be true )
  • ^ is a xor (exactly one condition needs to be true )
  • ( == compares objects by identity)
if (firstCondition && (secondCondition || thirdCondition))

There are also bitwise operators:

They are mainly used when operating with bits and bytes . However there is another difference, let’s take again a look at this expression:

firstCondition && (secondCondition || thirdCondition) 

If you use the logical operators and firstCondition evaluates to false then Java will not compute the second or third condition as the result of the whole logical expression is already known to be false . However if you use the bitwise operators then Java will not stop and continue computing everything:

firstCondition & (secondCondition | thirdCondition) 

so in my code, if I want to use both in my condition, is this what I have to do: if ((b.equals(«good»))||(b.equals(«it was Good») )) < System.out.println("Thank goodness"); >

Here are some common symbols used in everyday language and their programming analogues:

  • «,» usually refers to «and» in everyday language. Thus, this would translate to the AND operator, && , in Java.
  • «/» usually refers to «or» in everyday language. Thus, this would translate to the OR operator, || , in Java.

«XOR» is simply «x || y but both cannot be true at the same time». This translates to x ^ y in Java.

In your code, you probably meant to use «or» (you just used the incorrect «incorrect solution» :p), so you should use «||» in the second code block for it to become identical to the first code block.

You’re looking for the «OR» operator — which is normally represented by a double pipe: ||

 if (b.equals("good") || b.equals("it was good")) < System.out.println("Thank goodness"); >else if (b.equals("bad") || b.equals("it was bad"))

This is probably more answer than you need at this point. But, as several others already point out, you need the OR operator «||». There are a couple of points that nobody else has mentioned:

if («good».equals(b) || «it was good».equals(b))

The advantage of doing it this way is that the logic is precisely the same, but you’ll never get an NPE, and the logic will work just how you expect.

2) Java uses «short-circuit» testing. Which in lay-terms means that Java stops testing conditions once it’s sure of the result, even if all the conditions have not yet been tested. E.g.:

if((b != null) && (b.equals(«good») || b.equals(«it was good»)))

You will not get an NPE in the code above because of short-circuit nature. If «b» is null, Java can be assured that no matter what the results of the next conditions, the answer will always be false. So it doesn’t bother performing those tests.

Again, that’s probably more information than you’re prepared to deal with at this stage, but at some point in the near future the NPE of your test will bite you. 🙂

Источник

Как использовать тернарный оператор в Java?

Java-тернарный оператор является единственным условным оператором, который принимает три операнда. Это условный оператор, который обеспечивает более короткий синтаксис выражения if..else. Они компилируются в эквивалентное выражение if-else, то есть они будут точно такими же.

condition ? trueStatement : falseStatement
  1. Условие: первая часть — это раздел условия.
  2. trueStatement: второй код, который выполняется в случае условия первой части, .
  3. falseStatement: блок кода третьей части выполняется, если условие имеет значение false.

Тернарный оператор использует? и: символы. Первый операнд является булевым выражением; если выражение истинно, тогда возвращается значение второго операнда, иначе возвращается значение третьего операнда. Значение переменной часто зависит от того, является ли конкретное булево выражение истинным или нет.

Следующая программа Java оценивает условие, используя инструкцию if..else.

int x = 20, y = 10; if (x>y) System.out.println("x is greater than y"); else System.out.println("x is less than or equal to y");

То же самое мы можем сделать с тройным оператором в Java

int x = 20, y = 10; String result = x > y ? "x is greater than y" : "x is less than or equal to y";

Полный исходный код

public class TestClass < public static void main(String[] args) < int x = 20, y = 10; String result = x >y ? "x is greater than y" : "x is less than or equal to y"; System.out.println(result); > >

Вывод:

Вложенный тернарный оператор

Вы можете использовать Ternary Operator во вложенном выражении, например, в if..else.

Вложенный, если еще пример

public class TestClass < public static void main(String[] args) < int x=10; int y=20; int z=30; if( x >y ) < if ( x >z ) < System.out.println("x is greatest") ; >else < System.out.println("z is greatest") ; >> else < if ( y >z ) < System.out.println("y is greatest") ; >else < System.out.println("z is greatest") ; >> > >

Выход

Пример вложенного тернарного оператора

public class TestClass < public static void main(String[] args) < int x=10; int y=20; int z=30; String result = x >y ? x > z ? "x is greatest" : "z is greatest" : y > z ? "y is greatest" : "z is greatest"; System.out.println(result) ; > >

Источник

Multiple conditions in ternary conditional operator?

I am taking my first semester of Java programming, and we’ve just covered the conditional operator (? 🙂 conditions. I have two questions which seem to be wanting me to «nest» conditional operators within eachother, something that I could easily (yet tediously) do with if-else-if statements. 1) «Assume that month is an int variable whose value is 1 or 2 or 3 or 5 . or 11 or 12. Write an expression whose value is «jan» or «feb» or «mar» or «apr» or «may» or «jun» or «jul» or «aug» or «sep» or «oct» or «nov» or «dec» based on the value of month. (So, if the value of month were 4 then the value of the expression would be «apr».).» an idea I had looks something like this:

(month==1)?"jan":(month==2)?"feb": (month==3)?"mar": (month==4)?"apr": (month==5)?"may":(month==6)?"jun": (month==7)?"jul":(month==8)?"aug": (month==9)?"sep": (month==10)?"oct": (month==11)?"nov": (month==12)?"dec": 

(I know this isn’t a complete expression, but I’m not sure how to phrase the operator to handle so many conditions.) 2) Assume that credits is an int variable whose value is 0 or positive. Write an expression whose value is «freshman» or «sophomore» or «junior» or «senior» based on the value of credits. In particular: if the value of credits is less than 30 the expression’s value is «freshman»; 30-59 would be a «sophomore», 60-89 would be «junior» and 90 or more would be a «senior». again, I’ve been toying around and the best I can come up with is something like(and I’m probs missing some necessary parentheses):

I’ve Googled around and checked the database here, but I don’t THINK that there’s anything exactly like this question; forgive me if I’m wrong. The program (CodeLab) won’t take Switch-Case or the if-else-if solution, always suggesting I should be using the conditional ? : operator, but everywhere I’ve looked I haven’t figured out how to rig the operator to handle so many conditions. We aren’t far past this in the book, so if you guys could help me find a solution, it’d be great if it’s one that jives with the little bit I’ve learned so far.

Источник

Multiple conditions in ternary operators

First off, the question is «Write a Java program to find the smallest of three numbers using ternary operators.» Here’s my code:

I tried to use multiple conditions in the ternary operator but that doesn’t work. I was absent a few days so I’m not really sure what to do and my teacher’s phone is off. Any help?

At least in my experienced, just because you can write chained ternary statements, doesn’t mean you should. Also, what you have so far is very complicated, you should only need to compare the variables to one another once: int smallest = min(min(x, y), z) .

Math.min uses the ternary operator. the simplest is to staticly import this method and write smalledNum = min(x, min(y, z))

Consider modifying the assignment for the likely event when the professor makes «three» a variable. This will likely get you extra credit.

14 Answers 14

You can also remove the parenthesis:

Why does adding extra paranthesis gives error: unexpected type int min = x < y ? ((x < z) ? x : z) : ((y < z) ? y : z);

Since this is homework I’m not just going to give you the answer, but instead an algorithm so that you can work it out yourself.

First work out how to write min(x, y) using a single ternary operator.

Once you have that, change the following code for min(x, y, z) to use a ternary operator then substitute in the code for min(x, y) that you worked out from the previous step.

You’re testing for z, when you really don’t need to. Your ternary operator must be of form cond ? ifTrue : ifFalse;

so if you have multiple conditions, you have this:

cond1? ifTrue1 : cond2? if True2 : ifFalse2;

If you understand this, don’t look below. If you still need help, look below.

I also included a version that doesn’t nest them that is clearer (assuming you don’t need to have them nested. I sure would hope your assignment doesn’t require you to nest them because that’s pretty ugly!)

Here’s what I come up with:

class QuestionNine < public static void main(String args[]) < smallest(1,2,3); smallest(4,3,2); smallest(1,1,1); smallest(5,4,5); smallest(0,0,1); >public static void smallest(int x, int y, int z) < // bugfix, thanks Mark! //int smallestNum = (xpublic static void smallest2(int x, int y, int z) < int smallest = x < y ? x : y; // if they are equal, it doesn't matter which smallest = z < smallest ? z : smallest; System.out.println(smallest + " is the smallest of the three numbers."); >> 

Источник

Java двойной тернарный оператор

String securityAnswer = (man.getAge() >= 18 && (man.hasTicket() || man.hasCoupon()) && !man.hasChild()) ? «Проходите!» : «Вы не можете пройти!»; Ну это ещё достаточно читаемо )), не думаю что если запихать это в «if else» станет намного легче.

Если что, можно выводить на экран сразу с тернарником — строка 5 из последнего «правильного» подхода. Но если потом переменная нужна, то придется объявить.

Это для кого статья? Я получи ссылку на неё на 3-м уровне,но уже в первом примере много чего непонятно. Как я должен понять,что там вообще происходит? Всё,что до 17-й строки,что это такое? Да даже если с 17 смотреть. Вот-вот переход на 4-й уроветь. А что такое в параметрах main » String[] args» Почему ничего из этого не объясняется?

Подскажите, пожалуйста, возможно ли использовать тернарный оператор внутри цикла while? Если условие выполняется — вывод текста, если нет — завершение цикла. Как выводить один или второй текст, понятно. А как реализовать вывод текста или прерывание цикла не понятно.

JavaRush — это интерактивный онлайн-курс по изучению Java-программирования c нуля. Он содержит 1200 практических задач с проверкой решения в один клик, необходимый минимум теории по основам Java и мотивирующие фишки, которые помогут пройти курс до конца: игры, опросы, интересные проекты и статьи об эффективном обучении и карьере Java‑девелопера.

Этот веб-сайт использует данные cookie, чтобы настроить персонально под вас работу сервиса. Используя веб-сайт, вы даете согласие на применение данных cookie. Больше подробностей — в нашем Пользовательском соглашении.

Источник

Читайте также:  Python pandas удалить дубликаты строк
Оцените статью