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. 🙂
12.3. Java – Вложенный оператор if
В Java всегда допустимы вложенные операторы if-else, которые означают, что Вы можете использовать один оператор if или else внутри другого оператора if или else.
Синтаксис
Синтаксис вложенного оператора if..else в Java следующий:
Вы можете делать вложенным else if. else аналогично тому, как мы делали вложенным оператор if в Java.
Пример
Будет получен следующий результат:
Оглавление
- 1. Java – Самоучитель для начинающих
- 2. Java – Обзор языка
- 3. Java – Установка и настройка
- 4. Java – Синтаксис
- 5. Java – Классы и объекты
- 6. Java – Конструкторы
- 7. Java – Типы данных и литералы
- 8. Java – Типы переменных
- 9. Java – Модификаторы
- 10. Java – Операторы
- 11. Java – Циклы и операторы цикла
- 11.1. Java – Цикл while
- 11.2. Java – Цикл for
- 11.3. Java – Улучшенный цикл for
- 11.4. Java – Цикл do..while
- 11.5. Java – Оператор break
- 11.6. Java – Оператор continue
- 12. Java – Операторы принятия решений
- 12.1. Java – Оператор if
- 12.2. Java – Оператор if..else
- 12.3. Java – Вложенный оператор if
- 12.4. Java – Оператор switch..case
- 12.5. Java – Условный оператор (? 🙂
- 13. Java – Числа
- 13.1. Java – Методы byteValue(), shortValue(), intValue(), longValue(), floatValue(), doubleValue()
- 13.2. Java – Метод compareTo()
- 13.3. Java – Метод equals()
- 13.4. Java – Метод valueOf()
- 13.5. Java – Метод toString()
- 13.6. Java – Метод parseInt()
- 13.7. Java – Метод Math.abs()
- 13.8. Java – Метод Math.ceil()
- 13.9. Java – Метод Math.floor()
- 13.10. Java – Метод Math.rint()
- 13.11. Java – Метод Math.round()
- 13.12. Java – Метод Math.min()
- 13.13. Java – Метод Math.max()
- 13.14. Java – Метод Math.exp()
- 13.15. Java – Метод Math.log()
- 13.16. Java – Метод Math.pow()
- 13.17. Java – Метод Math.sqrt()
- 13.18. Java – Метод Math.sin()
- 13.19. Java – Метод Math.cos()
- 13.20. Java – Метод Math.tan()
- 13.21. Java – Метод Math.asin()
- 13.22. Java – Метод Math.acos()
- 13.23. Java – Метод Math.atan()
- 13.24. Java – Метод Math.atan2()
- 13.25. Java – Метод Math.toDegrees()
- 13.26. Java – Метод Math.toRadians()
- 13.27. Java – Метод Math.random()
- 14. Java – Символы
- 14.1. Java – Метод Character.isLetter()
- 14.2. Java – Метод Character.isDigit()
- 14.3. Java – Метод Character.isWhitespace()
- 14.4. Java – Метод Character.isUpperCase()
- 14.5. Java – Метод Character.isLowerCase()
- 14.6. Java – Метод Character.toUpperCase()
- 14.7. Java – Метод Character.toLowerCase()
- 14.8. Java – Метод Character.toString()
- 15. Java – Строки
- 15.1. Java – Метод charAt()
- 15.2. Java – Метод compareTo()
- 15.3. Java – Метод compareToIgnoreCase()
- 15.4. Java – Метод concat()
- 15.5. Java – Метод contentEquals()
- 15.6. Java – Метод copyValueOf()
- 15.7. Java – Метод endsWith()
- 15.8. Java – Метод equals()
- 15.9. Java – Метод equalsIgnoreCase()
- 15.10. Java – Метод getBytes()
- 15.11. Java – Метод getChars()
- 15.12. Java – Метод hashCode()
- 15.13. Java – Метод indexOf()
- 15.14. Java – Метод intern()
- 15.15. Java – Метод lastIndexOf()
- 15.16. Java – Метод length()
- 15.17. Java – Метод matches()
- 15.18. Java – Метод regionMatches()
- 15.19. Java – Метод replace()
- 15.20. Java – Метод replaceAll()
- 15.21. Java – Метод replaceFirst()
- 15.22. Java – Метод split()
- 15.23. Java – Метод startsWith()
- 15.24. Java – Метод subSequence()
- 15.25. Java – Метод substring()
- 15.26. Java – Метод toCharArray()
- 15.27. Java – Метод toLowerCase()
- 15.28. Java – Метод toString()
- 15.29. Java – Метод toUpperCase()
- 15.30. Java – Метод trim()
- 15.31. Java – Метод valueOf()
- 15.32. Java – Классы StringBuilder и StringBuffer
- 15.32.1. Java – Метод append()
- 15.32.2. Java – Метод reverse()
- 15.32.3. Java – Метод delete()
- 15.32.4. Java – Метод insert()
- 15.32.5. Java – Метод replace()
- 16. Java – Массивы
- 17. Java – Дата и время
- 18. Java – Регулярные выражения
- 19. Java – Методы
- 20. Java – Потоки ввода/вывода, файлы и каталоги
- 20.1. Java – Класс ByteArrayInputStream
- 20.2. Java – Класс DataInputStream
- 20.3. Java – Класс ByteArrayOutputStream
- 20.4. Java – Класс DataOutputStream
- 20.5. Java – Класс File
- 20.6. Java – Класс FileReader
- 20.7. Java – Класс FileWriter
- 21. Java – Исключения
- 21.1. Java – Встроенные исключения
- 22. Java – Вложенные и внутренние классы
- 23. Java – Наследование
- 24. Java – Переопределение
- 25. Java – Полиморфизм
- 26. Java – Абстракция
- 27. Java – Инкапсуляция
- 28. Java – Интерфейсы
- 29. Java – Пакеты
- 30. Java – Структуры данных
- 30.1. Java – Интерфейс Enumeration
- 30.2. Java – Класс BitSet
- 30.3. Java – Класс Vector
- 30.4. Java – Класс Stack
- 30.5. Java – Класс Dictionary
- 30.6. Java – Класс Hashtable
- 30.7. Java – Класс Properties
- 31. Java – Коллекции
- 31.1. Java – Интерфейс Collection
- 31.2. Java – Интерфейс List
- 31.3. Java – Интерфейс Set
- 31.4. Java – Интерфейс SortedSet
- 31.5. Java – Интерфейс Map
- 31.6. Java – Интерфейс Map.Entry
- 31.7. Java – Интерфейс SortedMap
- 31.8. Java – Класс LinkedList
- 31.9. Java – Класс ArrayList
- 31.10. Java – Класс HashSet
- 31.11. Java – Класс LinkedHashSet
- 31.12. Java – Класс TreeSet
- 31.13. Java – Класс HashMap
- 31.14. Java – Класс TreeMap
- 31.15. Java – Класс WeakHashMap
- 31.16. Java – Класс LinkedHashMap
- 31.17. Java – Класс IdentityHashMap
- 31.18. Java – Алгоритмы Collection
- 31.19. Java – Iterator и ListIterator
- 31.20. Java – Comparator
- 32. Java – Дженерики
- 33. Java – Сериализация
- 34. Java – Сеть
- 34.1. Java – Обработка URL
- 35. Java – Отправка Email
- 36. Java – Многопоточность
- 36.1. Java – Синхронизация потоков
- 36.2. Java – Межпоточная связь
- 36.3. Java – Взаимная блокировка потоков
- 36.4. Java – Управление потоками
- 37. Java – Основы работы с апплетами
- 38. Java – Javadoc
how to do an if statement with multiple conditions [duplicate]
Second of all, this is the way you use the || operator:
if(temp.equals("A") || temp.equals("a")) pit = 13;
An even better approach is :
if("A".equalsIgnoreCase(temp)) pit = 13;
Finally, as a note, bear in mind that the equality operator in Java is == , whereas = is the assignment operator.
Scanner input seems to be initialized with System.in so Scanner#nextLine won’t return null and temp won’t have null value thus NullPointerException won’t be thrown by usage of temp variable.
In java when using group condition operator, you must re-specify the value you are testing each time.
if(temp.equals("A") || temp.equals("a"))
Notice that I compared using the equals function as you are comparing Object and == will only compare the memory addres value.
Also since the multiple condition check the same letter with different case, you can use
if ("a".equals(temp.toLowerCase())
You want to use the equals method to compare strings
So your else if statement should look like this
else if(temp.equals(«D») || temp.equals(«d»))
if(temp == "A" || temp == "a") pit = 13;
A == B evaluates to a boolean (A == B) || C would therefore evaluate too boolean || String . Since String is not boolean, you get that error.
Note that since you’re comparing Strings and not primitives you should use equals:
if(temp.equals("A") || temp.equals("a")) pit = 13;
On Java 7 and above, better use a switch case with strings as
It becomes much more readable this way.
Might be worth noting that switch was available before Java 7, just that only since 7 is String supported in the clause.
Change your original code to the following:
System.out.print("Which pit would you like to select? "); String temp = input.nextLine(); < if(temp == "A" || temp == "a") pit = 13; else if(temp = "B" || temp == "b") pit = 12; else if(temp = "C" || temp == "c") pit = 11; else if(temp = "D" || temp == "d") pit = 10; else if(temp = "E" || temp == "e") pit = 9; else if(temp = "F" || temp == "f") pit = 12; else System.out.println("Not a valid pit!");
You have to specify which variable you are testing each time. What if you are testing this, for example:
String temp = "A"; String pmet = "B"; if(temp.equals("A") || pmet.equals("B")) < //Code to run here. >
In the previous code, you are saying "If temp is "A" OR pmet is "B", then run the section in the if statement". You can test more than just one variable using the || operator. Also, as previously stated, when you are testing string values, it is best to use ".equals(STRING)". For example, if(temp.equals("A")) would be a better way to code this. You will get the correct result, but it is not really the most appropriate way to code this.