我正在尝试编写一种方法,该方法可以采用起始小写字母和结尾小写字母并在该范围内生成随机字母。接下来,将随机字母分配给用户确定大小的数组的元素。到目前为止,只要起始字符是“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
任何帮助将不胜感激!