lundi 17 février 2020

Need to Convert Array Output to String Outside of a For Loop

I'm trying to practice encapsulation in prep for my Java SE 11 test and I need help getting my random name generator to work. Right now, I'm not concerned about the name being "valid" (a truly random name like Xvtwg is fine). I have built a loop where a random value between 3 and 10 is generated (length of name) and then a random index between 0 and 25 is chosen for each loop pass to grab a random letter of the alphabet. All of this works, and I am able to take the output array from the loop and turn it into a concatenated string in the loop. The problem occurs later when I need to call the local variable nameFinal as a value for the set function. I have tried to declare the output string both inside and outside the loop to no avail. I have also tried moving my output array outside of the loop (and redefining its output) with no dice. Specifically, the error says "nameFinal cannot be resolved to a variable." Here is my code:

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);
    }
}




Aucun commentaire:

Enregistrer un commentaire