0

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

Avigrail
  • 321
  • 2
  • 4
  • 14
  • 1st you should anyway test that user input 1 is a property/field of your class and actually it would be good to print possible options. There are limited number of fields to test so switch statement inside "for" loop can be used to distinguish which field should be used. – JosefN Dec 21 '13 at 23:44
  • I agree with you. I will list possible inputs to make sure the user hits my variables. Thanks for that! – Avigrail Dec 22 '13 at 00:12
  • The problem still exists. I get the idea behind your solution but it is exactly what I don't want to do. I want to deal with all inputs in only 1 or 2 lines. – Avigrail Dec 22 '13 at 12:38

1 Answers1

0

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.

Avigrail
  • 321
  • 2
  • 4
  • 14