我正在尝试用Java编写一个密码生成器,并且我确切地知道我想要实现这一点的方式。我的问题是,我不确定如何才能达到我想要的目标。
我想使用for循环来搜索一个字符串,获取一个随机字符,并将该字符存储在程序的内存中。然后,我想重复这个过程,直到字符串包含用户指定的字符数,并将结果字符串打印到终端。
我怎样才能以一种简单明了的方式做到这一点呢?
尝试1:
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
/**
* Write a description of class PasswordGenerator here.
*
* @author C.G.Stewart
* @version 06/06/18
*/
public class PasswordGenerator
{
private String input;
private int i;
private String newPass;
/**
* Constructor for objects of class Password
*/
public PasswordGenerator()
{
// initialise instance variables
input = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
ArrayList<String> Password = new ArrayList<String>();
Scanner pass = new Scanner(System.in);
}
/**
* This method generates a random alphanumeric string to be used as the new
* password
*/
public void generatePassword()
{
Random rnd = new Random();
for(i=1; i<=20; i++)
{
Math.random();
System.out.println(input.charAt(i));
}
//newPass = System.out.println(input.charAt(i));
}
/**
* This method takes the previously generated random alphanumeric string,
* and outputs it to the screen.
*/
public void newPassword()
{
System.out.println(newPass);
}
}
尝试2:
import java.util.Scanner;
import java.util.Random;
/**
* Write a description of class Password here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Password
{
// instance variables - replace the example below with your own
private String index;
/**
* Constructor for objects of class Password
*/
public Password()
{
// initialise instance variables
index="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Scanner pass = new Scanner(System.in);
}
//Returns a random alphanumeric string of an inputted length
public void printPassword()
{
for(int i=10; i<=20; i++)
{
while(i<=20)
{
Random rand = new Random();
char letter;
letter = index.charAt(i);
}
System.out.println(i);
}
}
}
发布于 2018-06-09 04:35:03
如果只是想从字符串中抓取一个随机字符,那么为什么需要使用for循环来搜索字符串呢?
为什么不直接生成一个随机整数并将其用作字符串的索引呢?
如下所示:
String str, password = "";
for (int i=0; i<passwordLength; i++){
Random rand = new Random();
int index = rand.nextInt(str.length());
password += str.charAt(index);
}
https://stackoverflow.com/questions/50767941
复制相似问题