我正在尝试为Java SE 11测试做准备中的封装,我需要帮助使我的随机名称生成器正常工作。现在,我不担心名称是否“有效”(像Xvtwg这样的真正随机名称就可以了)。我建立了一个循环,其中生成3到10之间的随机值(名称长度),然后为每个循环遍历选择0到25之间的随机索引以获取字母的随机字母。所有这些工作正常,并且我能够从循环中获取输出数组,并将其转换为循环中的串联字符串。稍后当我需要调用局部变量nameFinal作为set函数的值时,会出现问题。我试图在循环内外声明输出字符串都无济于事。我还尝试了将输出数组移到循环外(并重新定义其输出),但没有骰子。具体来说,错误显示为“ nameFinal无法解析为变量”。这是我的代码:
package RegressionTest;
import java.util.Arrays;
import java.util.Random;
public class Tester {
public static void main(String[] args) {
//Build random values
Random rand = new Random();
//Name random index 3-10 char
int nmax = 10;
int nmin = 3;
int rand1 = (int)(Math.random() * (nmax - nmin + 1) + nmin);
//Create random name from total number of letters
//Define Array of letters
String[] letters = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
//Create random index to pull a random letter over the length of the random index
int lmax = 25;
int lmin = 0;
//I have also tried declaring newName and nameFinal here
for(int i = 0; i <= rand1; i++) {
int randl = (int)(Math.random() * (lmax - lmin + 1) + lmin);
String[] newName;
newName[i] = letters[i];
String nameFinal = Arrays.toString(newName);
}
//Concatenate array of random letters into a "name"
//String nameFinal = Arrays.toString(newName);
//Age random number between 1 and 100
int amax = 100;
int amin = 1;
int rand2 = (int)(Math.random() * (amax - amin + 1) + amin);
//SSN random 9 digit number
int smax = 999999999;
int smin = 100000000;
int rand3 = (int)(Math.random() * (smax - smin + 1) + smin);
//Redefine outputs to random values
encapsulationPractice output = new encapsulationPractice();
output.setName(nameFinal);
output.setAge(rand2);
output.setSSN(rand3);
}
}
我对您的代码做了一些更改。希望对您有帮助!
public static void main(String[] args) {
//Build random values
Random rand = new Random();
//Name random index 3-10 char
int nmax = 10;
int nmin = 3;
int rand1 = (int)(Math.random() * (nmax - nmin + 1) + nmin);
//Create random name from total number of letters
//Define Array of letters
String[] letters = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
//Create random index to pull a random letter over the length of the random index
int lmax = 25;
int lmin = 0;
ArrayList<String> name = new ArrayList<>(5);
//I have also tried declaring newName and nameFinal here
for(int i = 0; i <= rand1; i++) {
int randl = (int)(Math.random() * (lmax - lmin + 1) + lmin);
name.add(letters[rand1]);
}
//Concatenate array of random letters into a "name"
//String nameFinal = Arrays.toString(newName);
//Age random number between 1 and 100
int amax = 100;
int amin = 1;
int rand2 = (int)(Math.random() * (amax - amin + 1) + amin);
//SSN random 9 digit number
int smax = 999999999;
int smin = 100000000;
int rand3 = (int)(Math.random() * (smax - smin + 1) + smin);
//Redefine outputs to random values
System.out.println(name.toString());
}