Java error: message "incompatible types"

I get an error in Java at compile time:

UserID.java:36: error: incompatible types
            + generator.nextInt(10);
            ^
  required: String
  found:    int

Here is the Java code:

public class UserID {

  private String firstName; 
  private String userId;  
  private String password;

  public UserID(String first) {
     Random generator = new Random();

     userId = first.substring(0, 3) + 
        + generator.nextInt(1) + 
       (generator.nextInt(7) + 3) + generator.nextInt(10);     //this works

     password = generator.nextInt(10) + generator.nextInt(10);   //Error is here

  } 
}

What is the cause of this error and how to fix it? Why doesn't this automatically push int to String?

+5
source share
4 answers

On the line, passwordyou add integers (when you want to concatenate them) and put them on the line without an explicit cast. You need to use Integer.toString ()

So,

password = Integer.toString(generator.nextInt(10) + generator.nextInt(10)
        + generator.nextInt(10) + generator.nextInt(10)
        + generator.nextInt(10) + generator.nextInt(10));

The reason it works in usernameis because you add strings for integers placed in a String, so it implicitly throws it into a String when concatenating.

+5
source

It is best to use StringBuilder,

StringBuilder sb=new StringBuilder();
sb.append(first.substring(0, 3));
sb.append(last.substring(0, 3));
sb.append(generator.nextInt(1));
sb.append(generator.nextInt(7) + 3);
sb.append(generator.nextInt(10));

userId=sb.toString();
+2

, "", :

password = "" + generator.nextInt(10) ...
+1

Look at the type of the return value generator.nextInt(), it returns int, but you are trying to assign it Stringto what it says: an incompatible type, you cannot assign an int to String.

0
source

All Articles