0

I have a java class Customer with constructor as Customer(string firstName, string lastName) and a getName() method that allow me to get the customer name from each Customer object

Then I have an input.txt file with first names and last names by lines as below example:

Alan, Walker

Tom, Hanks

How can I automatically read the first name and last name from each line above, and correspondingly create a Customer object for that person name?

Example: I want to the program to automatically read the first line "Alan, Walker" and create the object AlanWalker = new Customer("Alan", "Walker"), then do the same for 2nd line

Secondly, my 2nd task is to provide the user ability to give command from keyboard to get the name of the customer created. For example: the user can type "Alan Walker, print name" and the program will run AlanWalker.getName() to give the desired output as "Alan Walker". How can I implement this?

Null Reference
  • 11,260
  • 40
  • 107
  • 184
  • 1
    Does this answer your question? [How do I create a Java string from the contents of a file?](https://stackoverflow.com/questions/326390/how-do-i-create-a-java-string-from-the-contents-of-a-file) – OH GOD SPIDERS May 20 '20 at 14:33

2 Answers2

1

I have below written my solution to this problem which includes using a HashMap to access a specific object by a value. (HashMap) The below code will create a HashMap of Person objects against a name.

public static final HashMap<String, Person> people = new HashMap<>();

For these examples, the Person class below will be used:

public class Person {

    private String firstName, lastName;

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getName() {
        return firstName + " " + lastName;
    }

}

You can start by reading all of the file using a BufferedReader and creating an object for each line as seen here:

File txtFile = new File("names.txt");
BufferedReader txtFileReader = new BufferedReader(new FileReader(txtFile));
String line = null;
line = txtFileReader.readLine();

while (line != null) {
    String firstName = line.split(", ")[0];
    String lastName = line.split(", ")[1];

    Person person = new Person(firstName, lastName);
    people.put(person.getName(), person);

    line = txtFileReader.readLine();
}
txtFileReader.close();

This code will create a new instance of Person for each line of valid input in the file in the format <first_name>, <last_name>.

We will now have a HashMap which looks like the following:

"Alan Walker", PERSON OBJECT
"Tom Hanks", PERSON OBJECT

To then interact which each object according to user input, we can retrieve the object from the people HashMap using the user input Alan Walker, print name with the following code:

BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in));
String input = consoleInput.readLine();
String name = input.split(", ")[0];
Person chosenPerson = people.get(name);

From here you can perform actions on the object, for example if you wanted to get the name of the object you would do:

chosenPerson.getName()

Hope this helps.

CureMe
  • 170
  • 2
  • 9
0

In java, we can't create the dynamic variables but you can create the objects dynamically as shown below. What I suggest is use map and keep the key as the person's name and then store the customer object as value and when anybody uses scanner( just as an example ) to input the name then the application should check inside the map and should return the corresponding value that is customer object.

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

public class Demo {


    List<String> data = new ArrayList<>();

    {
        data.add("Abhishek");
        data.add("Alan");
    }

    public void demo()
    {

        data.forEach( name -> {

            Customer customerObj = null;
            try 
            {
                customerObj =  Customer.class.getConstructor(String.class).newInstance(name);
            } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                e.printStackTrace();
            }

            System.out.println(customerObj.getName());
        } );



    }

    public static void main(String[] args)
    {

        new Demo().demo();

    }
}
UnknownBeast
  • 979
  • 1
  • 6
  • 13