0

I'm trying to create a loop of 50 characters and then return the whole 50 characters as a String, but unfortunately the String is only returning the last letter, and not all 50 characters. getRandomUpperChar() is just a method I created to get a random Uppercase char value from 'A' to 'Z'.

public static String initializeKey(int num , int minNum, int maxNum) {
    String random = "";
    for(int j = 0; j <num; j++) {
        getRandomUpperChar();
        char Xp = getRandomUpperChar(minNum, maxNum);

        random = "" +  Xp;
        System.out.print(random);
    }
    return random;
}
1
  • Out of curiosity, what is the method call to getRandomUpperChar() with no args doing on line 4? Is your method overloaded? If so, what does the no-arg method do? Commented Nov 14, 2014 at 23:32

3 Answers 3

2

You are missing something very basic

random+= "" +Xp 
Sign up to request clarification or add additional context in comments.

2 Comments

Oh my goodness, I can't believe I didn't see that. Thank you so much kind sir.
You can also write random += Xp;. Looks much cleaner and it works, due to the correct random variable.
2

Well, replacing

random = "" +  Xp;

with

random = random +  Xp;

would make it work, but a better solution would be:

public static String initializeKey(int num, int minNum, int maxNum) {
  StringBuilder random = new StringBuilder();

  for(int j = 0; j < num; j++){
     char xp = getRandomUpperChar(minNum, maxNum);
     random.append(xp);
  }

  return random.toString(); 
}

1 Comment

string concatenation (random = random + xp) allocates at least 2 new Strings each time you do it, which tends to thrash the garbage collector. The method shown above allocates one StringBuilder and one String, and is much preferred.
1

Just replace your

random = "" +  Xp;

with

random +="" + Xp;

and you would be fine.

2 Comments

Thank you as well mattias! I knew it must be something simple, but I couldn't of the life of me figure it out!! Thank you!!
A tip for the future is to debug your code, when you run into problems like this one. Then you would easily spot where the problem is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.