简体   繁体   中英

How to put both an int variable and String Variable inside .equals() that matches with a Boolean variable?

I am new to Java.

How to put the int variable of int year = 1999 and the String variable of String name = "Tai" together inside name.equals(); so that boolean r gets true if the int and String values match boolean r values?

The boolean r values are "Tai", "John", 1999, 2000, 2001, and 2002.

I must use .equals(); and I cannot use any other alternative.

Java

public class example {
  public static void main(String[] args) {

   //boolean values are "Tai", "John", 1999, 2000, 2001, and 2002.
   boolean r = false;

   String name = "Tai";

   int year = 1999;
   
   //Boolean gets true if name.equals() values matches boolean values.  
   boolean r = name.equals(year and "Tai");


  }
}

For reference, here is a link of something similar I want to achieve but in Java with .equals(); :

Boolean Variables and If statement fails for true statements

in Java logical and is &&

So you write:

boolean r = name.equals("Tai") && year == 1999;

Note that primitives in java compares through == , while objects through .equals()

If you must use .equals() to match an integer and a string then, convert the int to String using String.valueOf(int) . Example :

public class example {
  public static void main(String[] args) {

   boolean r = false;
   String name = "Tai";
   int year = 1999;
   
   r = name.equals(String.valueOf(year));
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM