0

i am new to java. i want to add user input into a vector and i want to search them ....

Scanner input = new Scanner(System.in);
String Name;
String Address;
Name = input.nextLine();
Address = input.nextLine();

how to put those 2 input into a vector and those Name and Address must work like a pair i mean if i store Name = john and Address = Canada(whatever) ... if i search John it will show ... John from Canada. sumthing like this. and if i add like 50 name and address into that vector i want to search them by name ... how to do it?

as i dont know how vector works plz show me how to store user input and how to search them.

it will be kind if you show me the same thing in Arraylist.

jtfkyo
  • 83
  • 3
  • 9

1 Answers1

0

Java Vector is not commonly used anymore. You could use a combination of lists and maps, as explained in this post, but maybe you could just make Person objects with name and address and add them to an ArrayList in stead?

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args){

        List<Person> persons = new ArrayList<>();
        persons.add( new Person("John", "Canada") );
        persons.add( new Person("John", "USA") );
        persons.add( new Person("John", "Mexico") );

        //java 8
        persons.stream().forEach((p) -> {
            System.out.println("Name: " + p.getName() +", Address: "+ p.getAddress());
        });

        //java 7
        for(Person p : persons){
            System.out.println("Name: " + p.getName() +", Address: "+ p.getAddress());
        }

    }

}

class Person {

    private final String name;
    private final String address;

    public Person(String name, String address){
        this.name = name; 
        this.address = address;
    }

    public String getName() {
        return name;
    }

    public String getAddress() {
        return address;
    }

}
Community
  • 1
  • 1
hrmffffff
  • 100
  • 1
  • 6
  • how to do that ... making person object with name and address and add that object to an Arraylist or vector? – jtfkyo Sep 07 '14 at 12:59
  • http://stackoverflow.com/questions/4460788/java-arraylist-that-stores-userinput in this post he use 2 arraylist 1 for number and for name ... how can i do that by using 1 arraylist? is it possible? – jtfkyo Sep 07 '14 at 13:43
  • I've updated my answer to show you how to make Person objects. – hrmffffff Sep 07 '14 at 14:33
  • this is what i am looking for ... i have another question .... if i add many name and address and i want to search them from that arraylist how can i search them by name? – jtfkyo Sep 07 '14 at 15:08