我正在尝试编写一个方法,该方法可以采用起始小写字母和结束小写字母,并在该范围内生成随机字母。接下来,将随机字母分配给由用户确定的大小的数组的元素。到目前为止,只要起始字符为“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
非常感谢任何帮助!
答案 0 :(得分:5)
int randomInt = generator.nextInt(toChar - fromChar + 1) + fromChar;
答案 1 :(得分:3)
int randomInt = generator.nextInt(toChar - fromChar + 1) + 97;
不应该是: -
int randomInt = generator.nextInt(toChar - fromChar + 1) + fromChar;
答案 2 :(得分:0)
* 它会帮助你吗?如果你把'a'放在哪里,例如A它将会出现一个大的情况,然后你把它放在那里,它会为你提供一些字符,我把它放在b,从b开始。 *
public static void main(String [] args){
Random r = new Random();
System.out.print((char) ((r.nextInt(26) + 'b')) + " ");
System.out.println();
}