-3

I do not understand how to set multiple boolean values in a single if statement, nor am I certain if this is possible. I attempted to write out simple test code to experiment and found that I was confusing myself more.

import java.util.Scanner;

boolean t = false;
boolean f = false;
boolean a = false;

System.out.println("Enter T or F");
Scanner scan  = new Scanner(System.in);
String t_f = scan.nextLine();

if(t_f == "t"){
     t = true;
     a =false;
}
else if(t_f == "f"){
    f = true;
    a  = true;
}

if(t = true){
    System.out.println("true");
}
else if (f = true){
    System.out.println("false");
}
else if(a = true){
    System.out.println("test");
}

I am finding that if I enter 'f', "true" is printed, which shouldn't be happening as I've set it to print false if 'f' is entered. (for example) I've attempted to manipulate the if statements varying the use of 'else if' and 'if' however I have had no success. Clearly I am missing a fundamental concept here, if anyone could help it would be greatly appreciated.

Group2
  • 13
  • 5

2 Answers2

3

You need to use == for boolean comparison(or for primitive date types). = is the assignment operator.

if(t == true){

Also, since its boolean, you don't need to compare as well.

if(t){ // if requires a boolean so just using the boolean variable would do

And use equals() method for String comparisons. == with Strings compares the object references.

if(t_f.equals("t")){
Rahul
  • 44,383
  • 11
  • 84
  • 103
1

Use str1.equals(str2) to compare Strings.

if (t_f.equals("t"))

Remember that = is the assignment operator. You should use == to compare primitive types (int, boolean, float, double, ...). But since if statement expects a boolean as condition, you can simple use this:

if (t) // if (t == true)
...
if (!t) // if (t == false)
Community
  • 1
  • 1
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73