Question

When creating e.g an address book I also want a method for searching it. Imagine I go for an object like this:

public class someone {

private static someone [] addressBook = new someone[150];
private String firstName;
private String lastName;
private String address;
    //...

public someone(String firstName, String lastNameame, String adress/*,...*/){
    this.firstName=firstName;
            //...
}

Now I'm planning on searching for someone using user input and Scanner. First, the user should declare for what (s)he is searching in gerneral:

public static void searchSomeone(){

System.out.println("What do you want to search for?: ");
Scanner sc1 = new Scanner(System.in);
String userInput1 = sc1.next(); // e.g. userInput1="firstName"

Second, the user is asked for the exact value (s)he is searching for:

System.out.println("Enter a " + userInput1 + ": ");
Scanner sc2 = new Scanner(System.in);
String userInput2 = sc2.next(); // e.g. userInput2="Peter"  

    for (int i=1;i<150;++i){
            if(getAddressBook[i].**"Value of userInput1"**.contains(userInput2)){ // here is my problem!*
                    System.out.println("Congrats, we've found someone! ");
        }
    }
}
  • Is there a way to use the value of the input as a call for the member variable?

In this case the argument should 'become'

if(getAddressBook[i].firstName.contains(userInput2)){}

I tried to implement another method like getInputValue that simply returns the String but it didn't work here. If there is no such solution I will have to include code for every member variable separately which I really dont want to!

Hope you get my idea! And please be kind I'm quite new to forums. :P

Was it helpful?

Solution

FYI
What I was trying to do here is not possible within Java I guess. However Visual Basic provides a "var" keyword and also something called "generics". For everyone who has the same problem may find a solution there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top