Use array in another class and stop random data

问题: For a project in school we need to generate a list of data and the possibility to delete the data. My project consists of the following classes: The main method » ShowDat...

问题:

For a project in school we need to generate a list of data and the possibility to delete the data. My project consists of the following classes:

The main method » ShowData.java

public class ShowData {
    public static void main(String[] args) {
        // Show the menu
        Menu menu = new Menu();
        menu.Menu();
    }
}

The interface with the data » DataInterface.java

public interface DataInterface {
    // User firstname
    public final static String[] FIRSTNAME = new String[]{"Homer", "Otto", "Marge", "Lisa", "Maggie", "Patty", "Selma", "Ned", "Nelson", "Ralph"};    
    // User lastname
    public final static String[] LASTNAME = new String[]{"Simpson", "Flanders", "Bouvier", "Muntz", "Wiggum", "Burns", "Smithers", "Carlson", "Prince", "Mann"};
}

The "menu" to choose between generate, delete and exit » Menu.java

public class Menu {
    public void Menu() {
        boolean check = true;
        while(check) {                
            // Ask questions and read the answers
            System.out.println("Type 1 to generate names");
            System.out.println("Type 2 to delete generated names");
            System.out.println("Type 3 to exit program.n");            
            Scanner userInput = new Scanner(System.in);
            String input = userInput.nextLine();                
            // Load the classes or exit program
            switch(input) {
                case "1":
                    GenerateData genData = new GenerateData();
                    genData.GenData();
                    break;
                case "2":
                    DeleteData delData = new DeleteData();
                    delData.DelData();
                    break;
                case "3":
                    check = false;
                    break;
                default:
                    System.out.println("nWrong input!n");
            }                    
        }
        System.out.println("Program closed.");
    }    
}

The class where the list (array) is generated » GenerateData.java

public String[][] generateData() {

    UserName username = new UserName();
    UserMail usermail = new UserMail();

    System.out.print("nHow many names do you need?n");

    Scanner scanner = new Scanner(System.in);
    int userCount = scanner.nextInt();

    System.out.println("");

    // Create array
    String[][] userArray = new String[userCount][2];

    // Fill array
    for (int i = 0; i < userCount; i++) {
        userArray[i][0] = username.userName();
        userArray[i][1] = usermail.userMail();
    }

    // Print array
    for (String[] a : userArray) {
        for (String a1 : a) {
            System.out.println(a1);
        }
        System.out.println("--------------------------------");
    }
    System.out.println("n");

    return userArray;
}

The class to get the names » UserName.java

public class UserName implements DataInterface {        
    // Generate Firstname
    public String firstName() {
        Random randFirst = new Random();
        return FIRSTNAME[randFirst.nextInt(FIRSTNAME.length)];
    }

    // Updated
    public String fixedFirst() { 
        final String fixedFirst = firstName(); 
        return fixedFirst; 
    }

    // Generate Lastname
    public String lastName() {
        Random randLast = new Random();
        return LASTNAME[randLast.nextInt(LASTNAME.length)];
    }

    // Updated
    public String fixedLast() { 
        final String fixedLast = lastName(); 
        return fixedLast; 
    }

    // Build Username
    public String userName() {
        return firstName() + " " + lastName();
    }        
}

The class to build the email addresses » UserMail.java

public class UserMail extends UserName {        
    // Firstname and lastname from UserName class
    public String mailFirst() {
        return fixedFirst();
    }        
    public String mailLast() {
        return fixedLast();
    }        
    // Build mail address
    public String userMail() {
        return firstName().toLowerCase() + "." + lastName().toLowerCase() + "@springfieldmail.com";
    }        
}

And at last the class to delete in the array. » DeleteData.java

public class DeleteData {
    public void DelData() {            
        // Get array
        // If array is empty tell inform the user
        // If array isn't empty:    
        System.out.println("Which line do you want to delete?");
        Scanner scanner = new Scanner(System.in);
        int line = scanner.nextInt();
        if (line > array.length) {
            System.out.println("Wrong input");
        } else {
            System.out.println("Line " + line + " has been deleted.");
        }
    }
}

I omitted the lines for the package and the imports. It's already a lot of text.

As you can see I don't use the array in my DeleteData class because I don't know how to access the array.

And there's a second problem: I use the random first and last names to generate an email address but the addresses are random too. They should be the same as the first and last names. Any ideas how to solve this?

Updated the question


回答1:

Here:

public String firstName() {
    Random randFirst = new Random();
    return FIRSTNAME[randFirst.nextInt(FIRSTNAME.length)];
}      

Every time you run one of your methods in the UserName class, the method will return a new random value. That is a really bad idea, that might affect all things in your code.

When you create a new UserName(), then, once this one object should pick random values, but from there on, for that object, these initial values should stay fixed.

So you have to give that class two (final) fields, and you set up both fields once, at creation time, and then your methods turn into simple getters.

For the other problem: your generation class creates new arrays. To then "forget" about them. So, instead of having a public void GenData() method, you should have:

public String[][] generateUserData() {
... return ...

instead!

In other words: one class creates an array object, and returns that to your "main" class. And then, to "delete" that array, you can pass a reference for that array to the "delete" class.

Another approach could be:

  • "main" creates empty arrays for you
  • it passes that array to another class for filling
  • it passes that array to yet another class for "deleting" entries

Finally: another design issue. You modelled a UserName and UserMail (which is good). But then you use a "raw" array to pull those together. That doesn't make sense. You should create another classes that holds a UserName and a UserMail instance instead. And then have a one-dim array of that NamedUserWithMail objects!


回答2:

The Menu class should have a local reference to the generated array as long as the class is active in memory (i.e. the user is still interacting with your console shell). The GenerateData class should return the generated array back to the Menu, and then you can pass this local variable to the other methods.

  • 发表于 2019-01-17 01:24
  • 阅读 ( 191 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除