I have a phonebook program with one main and one PhoneBook class as follows
import java.util.Scanner;
public class JavaApplication9 {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
PhoneBook p = new PhoneBook();
String name;
String name2;
String number;
int sw;
do
{
System.out.println("Choose");
System.out.println("1. Input new contact and number info");
System.out.println("2. Search");
System.out.println("3. Show contacts and numbers");
System.out.println("4. exit");
sw = inp.nextInt();
switch (sw)
{
case 1: System.out.println("Input name");
name = inp.nextLine();
inp.nextLine(); //to bypass the nextLine-skip
System.out.println("Input number");
number = inp.nextLine();
p.addNumber(name, number);
break;
case 2: System.out.println("Input name to search");
name2 = inp.nextLine();
p.showNumbersOf(name2);
break;
case 3: p.show();
break;
case 4:
}
} while(sw!=4);
}
PhoneBook class
public class PhoneBook {
ArrayList<String> arrList = new ArrayList<>();
HashMap<String, ArrayList<String>> catalog = new HashMap<>();
String name;
String number;
public void addNumber(String aName, String aNumber)
{
name = aName;
if (catalog.get(name) == null)
{
catalog.put(name, new ArrayList());
}
catalog.get(name).add(aNumber);
catalog.put(name, catalog.get(name));
}
public void showNumbersOf(String aName)
{
name = aName;
if (catalog.containsKey(name))
{
for (String it1 : catalog.keySet())
{
if (aName.equals(it1))
{
System.out.println(catalog.get(it1));
}
}
}
else
{
System.out.println("No such contact");
}
}
public void show()
{
for (String name: catalog.keySet())
System.out.println(name + catalog.get(name));
}
}
So when I add a contact like Nick 5550100 and decide to show, it should print Nick[55501000] but it prints [55501000] (with a space where the name should be)
also when using showNumberOf it seems to skip the entire
name2 = inp.nextLine;
unless I comment out the previous inp.nextLine commands from case 1 and even then it has the exact same problem with show().
I can't get figure what I'm doing wrong when putting the entries in the HashMap and/or when recovering them so please help me.