0
  import java.util.Random;
  public class Test {
        public static void main(String[] args) {
            randomIDGenerator();
        }

     public static String randomIDGenerator() {
        Random r = new Random();

        char a = 0;
        for (int i = 0; i < 3; i++) {
             a = (char) (r.nextInt(26) + 'a');
        }
        int b = 0;
        for (int j = 0; j < 2; j++) {
            b = r.nextInt(10);
        }
        String h = "" + b;
        String n = a + h;

        System.out.println(n);
         return n;
      }
 }

I am writing a code in Java and I want my output to be 3 characters from a to z and 2 numbers from 0 to 9 (e.g. abc01) but the program gives me 1 character and 1 number (e.g. a1). Why does the program do this despite I've put 3 and 2 into loops? From all I know the first loop must operate 3 times and the second one must operate 2 times. So at the end my output have to be 3 characters and 2 numbers. Thanks!

kiner_shah
  • 3,939
  • 7
  • 23
  • 37

2 Answers2

1

char and int can store one value so use String as

  String a = "";
    for (int i = 0; i < 3; i++) {
         a += (char) (r.nextInt(26) + 'a');
    }
    for (int j = 0; j < 2; j++) {
        a += r.nextInt(10);
    }
    return a;
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
1

You generate your random items correctly, but you do not collect the results in a proper way. Each iteration of the loop writes over the results of prior iteration, leaving both a and b with the result of the last iteration.

I recommend using a StringBuilder to store characters as you generate them:

Random r = new Random();
StringBuilder res = new StringBuilder();
for (int i = 0; i < 3; i++) {
     res.append((char)(r.nextInt(26) + 'a'));
}
for (int j = 0; j < 2; j++) {
    res.append(r.nextInt(10)); // You could use the same trick with '0'
}
System.out.println(res);

Demo.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • I'll use your way in another work, but this one must be done as user Pavneet_Singh wrote below. But thank you very much, your answer will help me later. –  Dec 23 '17 at 16:06
  • @D.Rose [appending in a loop is one specific case when `StringBuilder` is more efficient](https://stackoverflow.com/a/4645155/335858). If you need a `String` instead of printing a string, you can always harvest it from `res` with `String str = res.toString();` – Sergey Kalinichenko Dec 23 '17 at 16:10