3

我正在尝试编写一种方法,该方法可以采用起始小写字母和结尾小写字母并在该范围内生成随机字母。接下来,将随机字母分配给用户确定大小的数组的元素。到目前为止,只要起始字符是“a”,我的代码似乎就可以工作。当起始字符不是“a”时,我不知道如何使它工作。我编写了这个完整的程序来尝试解决我的方法:

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

任何帮助将不胜感激!

4

3 回答 3

5
int randomInt = generator.nextInt(toChar - fromChar + 1) + fromChar;
于 2012-11-12T05:11:53.107 回答
3
int randomInt = generator.nextInt(toChar - fromChar + 1) + 97;

这不应该是:-

int randomInt = generator.nextInt(toChar - fromChar + 1) + fromChar;
于 2012-11-12T05:12:53.277 回答
0

*它会帮助你吗?如果你把'a'放在哪里,例如A,它会写一个大写字母,你把数字放在那里,它会给你一些字符,我把b放在那里,从b开始。*

公共静态无效主要(字符串[]参数){

    Random r = new Random();


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

    System.out.println();


}
于 2012-11-12T05:20:48.557 回答