For some reason when I run the following code the program prints out “JDN4” or “JDN16” when at all times I want it to be printing “JDN” followed by three numbers ranging from 0-9; for example, “JDN123” or “JDN045” or “JDN206”. What is wrong with the code?
import java.util.*;
public class Document2 {
public static void main(String[] args) {
String initials = "JDN";
int randomNumbers;
Random generator = new Random();
int randomNumber1 = generator.nextInt(9);
int randomNumber2 = generator.nextInt(9);
int randomNumber3 = generator.nextInt(9);
randomNumbers = randomNumber1 + randomNumber2 + randomNumber3;
String userName = initials + randomNumbers;
System.out.println("Your username is " + userName + ".");
}
}
Your problem is
randomNumbersis declared as anint, so when you use the+on the other ints, it will sum the integers rather than concatenate them.So, if we were to use your approach, we’d need a string:
But it would be a lot easier just to generate a number from 0-999 and pad it with zeroes:
Something else worth noting is that
Random.nextInt(n)generates a random number between 0 (inclusive) andn(exclusive), so you probably should be doing.nextInt(10)if you want a number between 0 and 9.