1

I am trying to write a program that would ask the user how many security codes he wants to generate, then it would output as many codes as he requested in an array.

The security code should be 7 characters long and have the following format: NNNNLLL, where N is a random number and L is a random upper case letter.

The method should create security codes with the above format by randomly selecting the characters, i.e. numbers and letters.

I am expecting the program to output something like this if a user selects to generate 4 codes:

“2394QAB” “2821TSZ” “7173AAY” “2236WQA”

I can only use the methods for this code learned in my course and I cannot use other libraries like regex, that is why I am trying it like this.

This is the code I have done so far:

import java.util.Random;
public class ItemChecker{

    private StringBuffer strBuff;
    private String[] codes;
    private String CodeLetters, CodeNumbers;
    private int[] RandomNums;

    public ItemChecker(){
            strBuff=new StringBuffer();
    }

    public String[] getCodes(int[] amount){
        codes=new String[amount.length];
        for(int i=0;i<amount.length;i++)
            {
            CodeLetters="";
            strBuff=new StringBuffer();
                for(int j=0;j<4;j++)
                    {
                        Random RandomNumber=new Random();
                        int randomIndex=RandomNumber.nextInt(RandomNums.length);

                        CodeNumbers.append(RandomNumber[randomIndex]);
                    }
                for(int j=0;j<3;j++)
                    {
                        Random RandomLetter=new Random();
                        char c =(char)(RandomLetter.nextInt(26)+'a');
                        CodeLetters+=c;
                    }
            codes[i]=CodeNumbers+CodeLetters;
        }
    }


}

My intention is to create 4 random digits and 3 random letters and add them together in a string to make the code. However, the code doesn't generate the random codes and I have no clue how to proceed from here.

Dan
  • 3,647
  • 5
  • 20
  • 26
Narika
  • 43
  • 5
  • 1
    Please [edit] your question to include a more detailed description of "doesn't quite do what I would like it to do". – Progman May 14 '22 at 11:37
  • What is `codes=item.getCodes;` supposed to be? This code can't be even compiled. – Progman May 14 '22 at 11:43
  • 1
    Variable names should begin in lowercase, so they don't get confused with class names, which start in uppercase. – Progman May 14 '22 at 11:46
  • @Progman it is supposed to be the get method of the application but I am unsure if I am using it correctly in this sense. – Narika May 14 '22 at 11:47
  • @Progman thanks for pointing out the variables, didn't notice at all that I used upper case :) – Narika May 14 '22 at 11:49
  • 1
    @Narika Stop vandalizing your question. Don't add `{Solved}` and absolutely don't remove the code! – Ted Klein Bergman May 14 '22 at 13:24
  • 2
    I don't know why this has been marked as duplicate and especially linked to that question. This was clearly a school or a university assignment as OP states "I can only use the methods learnt in my course". He/she was meant to write the actual code and not using a third party library to do it. Also, regex weren't even mentioned... – Dan May 14 '22 at 13:59

3 Answers3

4

Within your getCodes method there are a couple of mistakes. A StringBuiler would be more appropriate for this task, instead of using a StringBuffer or chaining strings with the + operator. As a matter of fact, each time you're performing a concatenation with the + operator you're creating a new string in memory, rather than working on a same instance, this is not that efficient. Also, when you're adding an offset to the random value representing an upper case letter, you're adding the lower case 'a', instead of the upper case 'A'.

In your program, you could define a static method to offer the code generation service as a general utility and then invoke it within your getCodes method.

In the utility method, you could declare a Random object to get random int values. Then, with a first for loop, you could generate random values between 0 included and 10 excluded, and append them to a StringBuilder object. The String class represents immutable objects, so you need to use a StringBuilder to build one. As said above, chaining strings with the + operator will create new instances at each concatenation, you're not working on the same object.

Then, with a second for loop you could generate random values from 0 to 27 excluded, add to every value the offset 65, representing the upper case 'A' letter (lower case 'a' has value 97), and then cast this int value to a char to get its character representation. Finally, append the char to your StringBuilder instance.

Here is an implementation:

public class Main {
    public static void main(String[] args) {
        System.out.println(getSecurityCode());
    }

    public String[] getCodes(int[] amount) {
        String[] codes = new String[amount.length];
        for (int i = 0; i < codes.length; i++) {
            codes[i] = getSecurityCode();
        }
        return codes;
    }

    public static String getSecurityCode() {
        Random rand = new Random();
        StringBuilder strBuilder = new StringBuilder();

        //Appending 4 random digits
        for (int i = 0; i < 4; i++) {
            //nextInt(10) returns a value between 0 (included) and 10 (excluded)
            strBuilder.append(rand.nextInt(10));
        }

        //Appending 3 random upper case letters
        for (int i = 0; i < 3; i++) {
            //rand.nextInt(27) returns a random value between 0 and 26 included to represent an alphabet letter.
            //This value is added with the offset 65 which represents the upper case A letter.
            //Finally, this value is cast as a char or else it would append its int value
            strBuilder.append((char)(65 + rand.nextInt(27)));
        }

        return strBuilder.toString();
    }
}
Dan
  • 3,647
  • 5
  • 20
  • 26
1

To simplify your code that generate the password you could use RandomStringUtils from org.apache.commons.lang3.RandomStringUtils like described in this great tutorial https://www.baeldung.com/java-random-string. You just have to generate 2 strings : One with 4 digits One with 3 letters to uppercase

And concat both.

Here's How

 public static String getSecurityCode() {
    //generate 4 numbers only
     String generatedNumbers = RandomStringUtils.random(4, false, true);
    //generate 3 letters only
     String generatedLetters = RandomStringUtils.random(3, true, false).toUpperCase();
     
     return generatedNumbers + generatedLetters;
}

Or with StringBuilder

public static String getSecurityCode2() {
        StringBuilder stb=new StringBuilder(7);
        //generate 4 numbers only
        stb.append(RandomStringUtils.random(4, false, true));
        //generate 3 letters only
        stb.append( RandomStringUtils.random(3, true, false).toUpperCase());
         
         return stb.toString();
    }
ScorprocS
  • 287
  • 3
  • 14
1

Another way of doing this is to utilize StringBuilder's appendCodePoint method for this:

int number= random.nextInt(10000);  //generate any number between 0 to 9999
StringBuilder builder=new StringBuilder();
for(int i=0;i<3;i++) {
            builder.appendCodePoint(65+random.nextInt(26));
}
String result=number+builder.toString();
System.out.println(result);
Ashish Patil
  • 4,428
  • 1
  • 15
  • 36