我的老师要求我们使用33到127之间的ASCII字符来生成n长度的密码。我迷路了,不知道从哪里开始。这就是我到目前为止所做的:
import java.util.*;
public class PasswordGenerator {
public static void main(String[]args){
Random random = new Random();
Scanner input = new Scanner(System.in);
System.out.print("Enter password length: ");
int length = input.nextInt();
StringBuilder password = new StringBuilder(length);
int count = random.nextInt(127-33+1)-33'
if(length<0) {
System.out.println(Invalid password length: "+length);
}
else {
for(int i = 33; i<126+1; i++) {
答案 0 :(得分:0)
您没有正确使用Random
对象,因为它可以生成负数。
这是实现您所描述内容的一种方式:
if(length<0) /*handle error*/;
StringBuilder password = new StringBuilder();
for(int i = 0; i < length ; i++) {
password.append((char) (random.nextInt(127-33+1)+33));
}
答案 1 :(得分:0)
这是更新版本:
public static void main(String[] args) {
Random random = new Random();
try(Scanner input = new Scanner(System.in);){
System.out.print("Enter password length: ");
int length = input.nextInt();
StringBuilder password = new StringBuilder();
if (length < 0) {
System.out.println("Invalid password length: " + length);
}
for(int i = 0 ; i < length ; i++){
password.append((char) (random.nextInt(127-33) + 33));
}
System.out.println(password.toString());
}
}
的变化: