【发布时间】:2020-04-30 04:37:19
【问题描述】:
我必须创建一个程序来读取要打印的字符数,它会打印随机字符(a-z、A-Z、0-9 以及像 !、&、$ 等字符)。并且要打印的第一个字符不能是数字(0-9)。
所以示例输出如下:
变量的长度? 20
a5fTnO$akP_a12BahsiO
这是我到目前为止所拥有的,但我被困住了,不知道我还能做些什么来让它发挥作用。我也不确定我是否走在正确的轨道上。
我会更容易创建一个字符串,然后从字符串中获取随机字符(如果可能的话)?
import java.util.Scanner;
public class VariableNameRandomGen{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("Length of the variable? ");
int num = sc.nextInt();
final int noOfChars = num;
final int charsPerLine = num;
for(int i = 0; i < noOfChars; i++){
char ch = getRandomCharacter();
if((i+i) % charsPerLine == 0)
System.out.println(ch);
else
System.out.print(ch);
}
}
public static char getRandomCharacter(char ch1, char 2){
return (char)(ch1 + Math.random() * (ch2 - ch1 + 1));
}
public static char getRandomUpperCaseLetter(){
return getRandomCharacter('A', 'Z');
}
public static char getRandomDigitCharacter(){
return getRandomCharacter('0', '9');
}
}
【问题讨论】: