[英]Java Phone Book won't accept input from 2 strings
这是我正在为 java 电话簿工作的项目。 我试图编译,但是当我尝试添加第二个字符串时,它只是跳过它。
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
HashMap<String, String> PhoneBook = new HashMap<String, String>();
while (true == true){
System.out.println("Main Menu: ");
System.out.println("1. Add to phonebook");
System.out.println("2. Remove from phonebook");
System.out.println("3. Read the phonebook");
System.out.println("4. Clear entire phonebook");
int choice = s.nextInt();
if (choice == 1) {
System.out.println("Please enter the name of the person: ");
String name = s.nextLine();
PhoneBook.put(name, "Blah");
System.out.println("Please enter the number of the person: ");
String number = s.nextLine();
PhoneBook.put(name, number);
}
}
}
这与您尝试插入重复条目有关
if (choice == 1) {
System.out.println("Please enter the name of the person: ");
String name = s.nextLine();
PhoneBook.put(name, "Blah"); //first entry of name
System.out.println("Please enter the number of the person: ");
String number = s.nextLine();
PhoneBook.put(name, number); //second duplicate entry!
}
A) 将具有无效值的键放入哈希映射然后重写该值似乎效率低下。
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
HashMap<String, String> PhoneBook = new HashMap<String, String>();
while (true == true){
System.out.println("Main Menu: ");
System.out.println("1. Add to phonebook");
System.out.println("2. Remove from phonebook");
System.out.println("3. Read the phonebook");
System.out.println("4. Clear entire phonebook");
int choice = s.nextInt();
if (choice == 1) {
System.out.println("Please enter the name of the person: ");
String name = s.nextLine();
System.out.println("Please enter the number of the person: ");
String number = s.nextLine();
PhoneBook.put(name, number);
}
}
}
B)我认为这应该可以帮助您解决问题,但如果没有,请告诉我,我可以重新编辑我的答案。 我认为你只是把值放在同一个键上,这就是为什么你认为你没有得到第二个值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.