2

I wrote a short code that declares 6 reference variables from a class named 'ChosenCompanies' to practice classes and constructors in Java.

It is the following:

public static void main(String[] args) {

    String[] FinalCompaniesName = new String[6];

    ChosenCompanies com1 = new ChosenCompanies();
    ChosenCompanies com2 = new ChosenCompanies();
    ChosenCompanies com3 = new ChosenCompanies();
    ChosenCompanies com4 = new ChosenCompanies();
    ChosenCompanies com5 = new ChosenCompanies();
    ChosenCompanies com6 = new ChosenCompanies();

    Scanner scanner = new Scanner(System.in);
    int choice;
    int count = 1;
    while(count <= 2) {
        switch(count) {
        case 1:
            System.out.println("Choose one:");
            System.out.println("1. " + com1.name);
            System.out.println("2. " + com2.name);
            System.out.println("3. " + com3.name);
            choice = scanner.nextInt();
            switch(choice) {
            case 1:
                FinalCompaniesName[0] = com1.name;
                break;
            case 2:
                FinalCompaniesName[0] = com2.name;
                break;
            case 3:
                FinalCompaniesName[0] = com3.name;
                break;
            }
        break;
        case 2:
            System.out.println("Choose one:");
            System.out.println("1. " + com4.name);
            System.out.println("2. " + com5.name);
            System.out.println("3. " + com6.name);
            choice = scanner.nextInt();
            switch(choice) {
            case 1:
                FinalCompaniesName[1] = com4.name;
                break;
            case 2:
                FinalCompaniesName[1] = com5.name;
                break;
            case 3:
                FinalCompaniesName[1] = com6.name;
                break;
            }
            break;
        }    
        count++;
    }
        System.out.println("You have chosen: "
 + FinalCompaniesName[0] + ", " + FinalCompaniesName[1]);

}

As you can see from the above code, these two parts are almost the same except for the names of reference variables(com1, com2, com3, com4...):

part 1:

        switch(count) {
        case 1:
            System.out.println("Choose one:");
            System.out.println("1. " + com1.name);
            System.out.println("2. " + com2.name);
            System.out.println("3. " + com3.name);
            choice = scanner.nextInt();
            switch(choice) {
            case 1:
                FinalCompaniesName[0] = com1.name;
                break;
            case 2:
                FinalCompaniesName[0] = com2.name;
                break;
            case 3:
                FinalCompaniesName[0] = com3.name;
                break;
            }
         break;

part 2:

        case 2:
            System.out.println("Choose one:");
            System.out.println("1. " + com4.name);
            System.out.println("2. " + com5.name);
            System.out.println("3. " + com6.name);
            choice = scanner.nextInt();
            switch(choice) {
            case 1:
                FinalCompaniesName[1] = com4.name;
                break;
            case 2:
                FinalCompaniesName[1] = com5.name;
                break;
            case 3:
                FinalCompaniesName[1] = com6.name;
                break;
                }
            break;
        }    

I am wondering if I can minimize the amount of the code above by using a for or while loop, since the name of the reference variables are increased by 1, like integer 'i' in a common for statement.

In short, is it possible to declare reference variables by using loop?

  • 2
    Make that part a method that takes those 3 objects as arguments. – rdas May 27 '19 at 06:26
  • Will the code in part 2 even be executed? Your `while` condition passes only if `count < 2`, and how will the `case 2` part run? – Harshith Rai May 27 '19 at 06:38
  • Yes, the code in part 2 is executed and I checked the result just few seconds ago. I had the same doubt as yours and made the while condition (count <=2) at first, but with that condition the console showed the code in part 2 twice. – Eunyoung Roh May 27 '19 at 06:42
  • I got why the code is executed; it is because I didn't add a break statement for the switch(count) statement. I fixed the original code since it's quite confusing. – Eunyoung Roh May 27 '19 at 06:54
  • Note that you should follow the Java Naming Conventions: variable names are always written in camelCase. So `FinalCompaniesName` should be `finalCompaniesName`. – MC Emperor May 27 '19 at 07:14

2 Answers2

1

It is not possible in Java to create dynamic variables (but with reflections, see here)

You can create an array and use the i as index like chosenCompanies[i].

Otherwise you can use lists or maps.

Edit:

That would e.g. look like this. Apart from the sence of the code, this example shows only how you would use an array:

    String[] choosenCompanieNames = new String[2]; // you only store two values, not 6 values

    //lets store the values to chose in arrays
    String[] possibleCompanieNames = new String[6]; // 6 possible values to choose (com1 - com6)
    possibleCompanieNames[0] = "com1";
    possibleCompanieNames[1] = "com2";
    possibleCompanieNames[2] = "com3";
    possibleCompanieNames[3] = "com4";
    possibleCompanieNames[4] = "com5";
    possibleCompanieNames[5] = "com6";

    //I deleted the while loop, as it only has two ways and every way has its own code. 

    Scanner scanner = new Scanner(System.in);
    int choice;

    System.out.println("Choose one:");
    System.out.println("1. " + possibleCompanieNames[0]);
    System.out.println("2. " + possibleCompanieNames[1]);
    System.out.println("3. " + possibleCompanieNames[2]);
    choice = scanner.nextInt();
    choosenCompanieNames[0] = possibleCompanieNames[choice-1]; //you must subtract one, as the array index starts at 0 and ends on 5

    System.out.println("Choose one:");
    System.out.println("1. " + possibleCompanieNames[3]);
    System.out.println("2. " + possibleCompanieNames[4]);
    System.out.println("3. " + possibleCompanieNames[5]);
    choice = scanner.nextInt();
    choosenCompanieNames[1] = possibleCompanieNames[3+choice-1]; //here you want com4, com5 and com6, so you can e.g. add 3 to index and substract one like code above. Or better add only 2, as 3-1=2


    System.out.println("You have chosen: "
         + choosenCompanieNames[0] + ", " + choosenCompanieNames[1]);
heiwil
  • 612
  • 4
  • 8
  • Thank you for the answer. But since I started to learn Java only a month ago, I don't get what do I have to do with the array you mentioned. Did you mean the array that stores reference variables? (I wonder if it is possible) or did you mean to name reference variables like "chosenCompanies[i]' from the array named 'chosenCompanies'? (I also wonder if it is possible) – Eunyoung Roh May 27 '19 at 06:38
  • 2
    Eunyoung, you've already demonstrated in your code that you know how to declare and create an array; because you've done it with `finalCompaniesName`. Now all you have to do is exactly the same thing with `chosenCompanies`. – Dawood ibn Kareem May 27 '19 at 06:44
  • See my edit. It shows one way how to do this with arrays. – heiwil May 27 '19 at 06:52
  • 1
    I saw your edit. I think the reason why I was so confused was because I still wanted to create dynamic variables and magically minimize the amount of code, even after reading your answer that says it is not possible(unless I use reflections). However, after checking the edit, your way that uses an array to store the possible company names makes sense and it would be easier for me to maintain the code since I can see the stored values at the top. Thank you. – Eunyoung Roh May 27 '19 at 07:06
1

Your example is confusing so I don't know what exactly are you trying to accomplish, but here is an example of how to prompt the user to select a new name for each company from a list of existing company names:

    public class Company {

    /**
     * Array of available company names used to construct
     * initial companies. These names are also used as possible
     * choices when changing company names through {@link #changeCompanyNames()}
     */
    private static final String[] COMPANY_NAMES = new String[]
            { "Alphabet", "Microsoft", "IBM", "Amazon", "Oracle", "Apple" };

    /**
     * <p>
     * Array of Company objects initialized with a fixed number of
     * new companies equal to the number of String entries in {@link #COMPANY_NAMES}.
     * </p><p>
     * Each company entry will inheriting a name from the mentioned array
     * in the initialization process done in {@link #initializeCompanies()}
     * </p>
     */
    public static final Company[] COMPANIES = initializeCompanies();

    private String name;

    /**
     * Internal constructor with private access to
     * prevent class construction outside this class
     */
    private Company(String name) {
        this.name = name;
    }

    /**
     * Should only be used internally on class loading to
     * construct an array of companies from a list of company names.
     */
    private static Company[] initializeCompanies() {

        Company[] companies = new Company[COMPANY_NAMES.length];
        for (int i = 0; i < COMPANY_NAMES.length; i++) {
            companies[i] = new Company(COMPANY_NAMES[i]);
        }
        return companies;
    }

    /**
     * Change any or all company names by prompting the user to choose
     * a new name for each company from the list of available companies.
     */
    public static void changeCompanyNames() {

        java.util.Scanner scanner = new java.util.Scanner(System.in);
        /*
         * Create a new array of company names that is identical to the existing
         * array of company names. We will change names here on user input and
         * then update each new company name to values from this array.
         */
        final String[] finalCompanyNames = COMPANY_NAMES.clone();
        /*
         * Iterate through an array of companies with a for-loop
         * accessing and processing each company entry
         */
        for (int i1 = 0; i1 < COMPANIES.length; i1++)
        {
            /* Prompt the user to choose a new company name for the
             * company at index i1 from COMPANIES array.
             */
            System.out.printf("Choose a new company name for %s company:%n", COMPANIES[i1].name);
            /*
             * Again iterate through all companies and print their names to
             * console offering the user a list of possible names to choose from
             */
            for (int i2 = 0; i2 < COMPANIES.length; i2++) {
                System.out.printf("%d. %s%n", i2 + 1, COMPANIES[i2].name);
            }
            /*
             * Get user input and validate it, then either update the array of
             * final names with the new entry or print an error and move the index
             * to the previous position if the input was an invalid number
             */
            int input = scanner.nextInt();
            if (input > 0 && input <= COMPANIES.length) {
                finalCompanyNames[i1] = COMPANY_NAMES[input - 1];
                System.out.println("You have choosen company name " + finalCompanyNames[i1]);
            }
            else {
                System.out.printf("Error: input is not in range (1-%d)%n", COMPANIES.length);
                /*
                 * It's imperative that we move the index to the previous
                 * position so we can iterate over this company entry again
                 */
                i1 -= 1;
            }
        }
        // Print simple line separator
        System.out.println("");

        /* Print each choosen name that is different then the original
         * company name and update the appropriate company name field value
         */
        for (int i = 0; i < finalCompanyNames.length; i++)
        {
            if (!finalCompanyNames[i].equals(COMPANY_NAMES[i])) {
                System.out.printf("Company %s has changed name to %s%n", COMPANY_NAMES[i], finalCompanyNames[i]);
                COMPANIES[i].name = finalCompanyNames[i];
            }
        }
    }
}

Example console output after the user is done choosing:

Company Alphabet has changed name to IBM
Company Microsoft has changed name to Amazon
Company IBM has changed name to Alphabet
Company Amazon has changed name to Oracle
Company Oracle has changed name to Microsoft
Company Apple has changed name to Amazon

Here we are able to set any number of companies and let the user choose any of the offered names for them. The code might look a tad bit daunting for a beginner but this is actually the simplest way of doing this without involving any of the more complex Java concepts into play.

Feel free to ask any questions regarding this implementation. I will be quite happy to help out.

EDIT: Updated the code to include detailed comments and a more comprehensive structure that is easier to understand and fixed an indexing issue.

Matthew
  • 1,905
  • 3
  • 19
  • 26
  • Hi, Matthew. Thanks for the new implementation and explanation. I am now trying to understand your code and I believe it would help me a lot once I finish reading it. And I have one question for now: What does "ChosenCompanies[] companies" mean? I think ChosenCompanies is the name of the current class and [] is used for an array (at least from what I've learned so far), so the entire form - "ChosenCompanies[] companies" - is confusing me. Can you give me a bit of hint about that line so that I can google it and learn further? Thank you in advance :) – Eunyoung Roh May 27 '19 at 08:08
  • I've updated the code to include detailed comments and a more comprehensive structure that is easier to understand so things should be a lot more clear now. Concerning your question about that array, it's just a simple array of objects of a custom class called `Company`, I would suggest reading the official tutorial about arrays available here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html. That might be a good place to start learning more about arrays. – Matthew May 27 '19 at 09:25
  • If you feel my answer provides more insight into basic ways of handling simple array and better addresses your question in general feel free to choose my answer as the accepted one. I am relatively new to actually actively participating on this website and would be very happy with my first accepted answer. – Matthew May 27 '19 at 09:33
  • Your answer is really helpful and well-written, I learned a lot while examining your comments in the code. However, when I run your program and insert '6' to choose Apple for a company name, it shows 'Error: input is not in range (1-%d)%n'. I fixed a little bit (input > 0 && input < COMPANIES.length *+ 1*) and now it works well on my machine, but I thought it would be nice to tell you about that, since I wanted to say 'thank you for such a thorough answer' while not violating the forum rule which doesn't recommend us to write only a 'thank you' comment. :) – Eunyoung Roh May 27 '19 at 10:44
  • Glad I could help and thank you for accepting my answer. I've fixed the posted code and would suggest using `input > 0 && input <= COMPANIES.length` instead of `input > 0 && input < COMPANIES.length + 1` as it's a bit more clean. – Matthew May 27 '19 at 10:55