-1
public static void main(String[] args)
    {
        final int ELEMENTS = 13;
        //int[] array = new int[ELEMENTS];
        char[] array1 = new char[ELEMENTS];
        printWord(array1);

    }

    public static void printWord(char[] array)
    {
        Random random = new Random();
        int[] letters = new int[array.length];
        for(int index = 0; index < array.length; index++)
        {
            letters[index] = random.nextInt(122)+97;
            System.out.println(letters[index]);

        }
        System.exit(0);
    }

My problem occurs within the method printword(). When it assigns a random integer to letters in the for loop the random method adds the 97 to the 122 instead of having a random number between 97-122. Question: I've always constructed my random method this way, and now its not working why? Can you help me with an alternative?

user1953222
  • 110
  • 1
  • 7

2 Answers2

0

To generate a random number between two given values, use the following technique

int lowerBound = 97;
int upperBound = 127;
int randomValueInBound = random.nextInt(upperBound-lowerBound) + lowerBound

Also, you have to cast your integers as chars to display the characters but I guess you already know that

 System.out.println((char)letters[index]);
Saif Asif
  • 5,516
  • 3
  • 31
  • 48
0

You have got a little issue with your code this might help you

public static void printWord(char[] array)
{
    Random random = new Random();
    int[] letters = new int[array.length];
    for(int index = 0; index < array.length; index++)
    {
        letters[index] = random.nextInt((122+1) - 97) + 97;
        System.out.println((char)letters[index]);

    }
    System.exit(0);
}

please refer for more information

Community
  • 1
  • 1
SparkOn
  • 8,806
  • 4
  • 29
  • 34