Question

I am trying to write a method that can take a starting lowercase letter and an ending lowercase letter and generate random letters in that range. Next, the random letters are assigned to the elements of an array of a size determined by the user. So far, my code seems to work as long as the starting character is 'a'. I can't figure out how to make it work when the starting character is not 'a'. I wrote this complete program to try to troubleshoot my method:

import java.util.Random;
import java.util.Scanner;
public class Add
{
    public static void main( String[] args )
    {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter array size: ");
        int arraySize = scan.nextInt();
        char charArray[] = new char[arraySize];

        int fromChar;
        int toChar;
        do
        {
        System.out.print("Enter first character: ");
        String line = scan.next();
        fromChar = line.charAt(0);

        System.out.print("Enter second character: ");
        line = scan.next();
        toChar = line.charAt(0);

        Random generator = new Random();
        for(int i = 0; i < arraySize; i++)
        {
            int randomInt = generator.nextInt(toChar - fromChar + 1) + 97;
            //System.out.print(randomInt + " | "); //used to print unicode values
            charArray[i] = (char)(randomInt);
        }
        System.out.println(charArray);
    }
        while(true);

    } // end of main
}// end of class

Any help would be greatly appreciated!

Was it helpful?

Solution

int randomInt = generator.nextInt(toChar - fromChar + 1) + fromChar;

OTHER TIPS

int randomInt = generator.nextInt(toChar - fromChar + 1) + 97;

shouldn't this be: -

int randomInt = generator.nextInt(toChar - fromChar + 1) + fromChar;

*its will help you? if you will put where the 'a' for example A it will rand a UPPER CASE, and you put there number it will rand for you some char, i put there b, to start from b. *

public static void main(String[] args) {

    Random r = new Random();


    System.out.print((char) ((r.nextInt(26) + 'b')) + " ");

    System.out.println();


}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top