java - 生成随机字符数
问题描述
我必须创建一个读取要打印的字符数的程序,它将打印随机字符(az、AZ、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');
}
}
解决方案
您可以使用示例字符串包含您想要的所有字符:
final static String SAMPLE = "abcd... xyzABCD...XYZ ()?!;"
final static String NUM = "0123456789";
public static char getRandomCharacter(String s){
return s.charAt( new Random(s.lenght()).nextInt());
}
而在主要
String rs = "" + getRandomCharacter(SAMPLE);
for(int i = 1; i < noOfChars; i++){
char ch = getRandomCharacter(SAMPLE + NUM);
rs+= ch;
}
System.out.print(rs);
推荐阅读
- arrays - 从工作表创建数组并使用 For Each 循环
- docker - 如何在 ubuntu 中使用 fscrawler?
- r - group_by(月和年)和 summarise_if 不会留下单个月的平均值
- r - gt表R正文中的下标和上标
- swift - 关于 CSSearchQuery 和 Spotlight 的问题
- java - 如何使用 java sound api 增加来自 targetdataline 的音频响度?
- excel - 将 Excel 范围作为图片复制到剪贴板
- swiftui - SwiftUI 文本字段可以与可选绑定一起使用吗?: 无法转换类型“绑定”的值
'到预期的参数类型'绑定 ' - java - Mybatis mapper list 返回结果重复
- c# - .Net 和 as .Net Core 是同一个框架但名称不同吗?