Reputation: 7
This is a simple code to get person's info. For example, when I type in enter#runnan#male#23#Earth it would save the data in LinkedHashMap. Also when I type in search#runnan it would search the datas in LinkedHashMap and find name runnan then print the whole info. I somehow managed to the saving part but whenever I try to search, it only shows the file address of the data.
import java.util.*;
public class PersonManage {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
Map<String, Person> ps = new LinkedHashMap<String, Person>();
ps.put("Runnan", new Person("Runnan","Male", 23, "Earth"));
while(true){
System.out.println("Person Manager > ");
String in = scanner.nextLine();
String[] arr = in.split("#");
if(arr[0].equals("enter")){
String name = arr[1];
String gender = arr[2];
int age = Integer.parseInt(arr[3]);
String address = arr[4];
ps.put(arr[1], new Person(arr[1],arr[2],age,arr[4]));
System.out.println(arr[1]+"Saved");
continue;
}
else if(arr[0].equals("search")){
System.out.println(ps.get(arr[1]).toString());
continue;
}
else if(arr[0].equals("exit")){
break;
}
else {
System.out.println("write in format of enter#name#gender#age#address");
System.out.println("or search#searchingname");
}
}
}
This is the overriden class.
public class Person {
String name;
String gender;
int age;
String address;
public Person(String string, String string2, int i, String string3) {
// TODO Auto-generated constructor stub
this.name = string;
this.gender = string2;
this.age = i;
this.address=string3;
}
public String toString(){
String t = name+gender+age+address;
return t;
}
}
Any help would be grateful to me and will so much be appreciated.
Upvotes: 0
Views: 831
Reputation: 2049
I tried your code with these inputs:
enter#Jhon#Men#23#Moon
enter#Mongo#Men#101#Jupiter
enter#Paul#Men#23#Earth
Then, when I used search:
search#Paul
I got:
PaulMen23Earth
Maybe you can edit your toString()
method:
public String toString(){
String t = "name: " + name+ ",\n" + "gender: " + gender+ ",\n" +
"age: " + age + ",\n" + "address: " + address;
return t;
Besides you should add a control when a name is not present in your list:
else if(arr[0].equals("search")){
if(ps.get(arr[1])!= null) {
System.out.println(ps.get(arr[1]).toString());
continue;
}
else {
System.out.println("This name is not present. You can add it using \"enter\" command");
}
Upvotes: 0
Reputation: 3836
In order to print all values from map to the console you should write something like:
else if (arr[0].equals("listAll")) {
for (Person person : ps.values()) {
System.out.println( person );
}
continue;
}
Or more concise version with Java 8 Stream API
features:
else if (arr[0].equals("listAll")) {
map.values().forEach(System.out::println);
continue;
}
Upvotes: 1