New at coding, and I'm running some basic exercises to get used to the language. In this exercise I'm trying to generate a phone number with the following restrictions:
- 1st 3 digits cannot contain an 8 or 9
- 2nd set of 3 digits cannot be higher than 742
I've seen suggestions to add an empty string (which I have), but I don't understand why that works. For now, I'll be sticking with the following, even though I don't fully understand why it works.
num1 = rand.nextInt(7) + 1;
num2 = rand.nextInt(7) + 1;
num3 = rand.nextInt(7) + 1;
num4 = rand.nextInt(643) + 100;
num5 = rand.nextInt(1001) + 1000;
String number = "" + num1 + num2 + num3 + "-" + num4 + "-" + num5;
System.out.print("Your assigned phone number is: " + number);
EDIT: NEW CODE INCLUDES sb.append
StringBuilder sb = new StringBuilder();
int num1, num2, num3, num4, num5;
num1 = rand.nextInt(7) + 1;
num2 = rand.nextInt(7) + 1;
num3 = rand.nextInt(7) + 1;
num4 = rand.nextInt(643) + 100;
num5 = rand.nextInt(1001) + 1000;
sb.append(num1);
sb.append(num2);
sb.append(num3);
sb.append("-");
sb.append(num4);
sb.append("-");
sb.append(num5);
//String number = "" + num1 + num2 + num3 + "-" + num4 + "-" + num5;
System.out.print("Your assigned phone number is: " + sb.toString());
@Serge 's answer worked for me. Though it does seem to require more coding with all the sb.append calls I have to include. I've yet to learn about the StringBuilder class, but it definitely seems to be helpful. Thank you, everyone.