Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java error: "incompatible types" message

I am getting an error in Java during compilation:

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 reason for this error and how do I fix it? Why is it not automatically promoting the int to a String?

like image 311
user951901 Avatar asked Sep 19 '11 03:09

user951901


People also ask

What is type error in Java?

There are 3 types of Errors: Syntax Error. Runtime Error. Logical Error.


1 Answers

On the password line, you're adding Integers(When you want to be concatenating them) and putting it into a string without an explicit cast.You'll have to use Integer.toString()

So like this

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 username is because you have Strings being added to integers the put into a String, so it's implicitly casting it to a String when concatinating.

like image 172
Nicholas Avatar answered Oct 21 '22 15:10

Nicholas