我正在尝试创建一个按姓氏排序的联系人列表。当我尝试使用 lastName.put(last,array)将每个联系人存储到TreeMap中时,一切正常。但是,TreeMap不会在以后的while循环中存储信息。谁能帮我这个?如果我使用这个论坛不正确,请原谅我。我是Java的新手。
package Assignment;
import java.io.*;
import java.util.*;
import java.nio.*;
public class ContactList
{
public static void main(String[] args)
{
try
{
Scanner input = new Scanner(System.in);
long storage = 99999;
int choice;
int secondChoice;
boolean exit = true;
int i = 0;
System.out.println("Would you like to add a contact?"
+ " Type 1 for yes");
choice = input.nextInt();
if(choice == 1)
{
while(exit == true)
{
TreeMap <String, List<String>> lastName = new TreeMap <String, List<String>>();
List <String> array = new ArrayList <String>();
System.out.println("Plese add first name");
array.add(input.next());
System.out.println("Plese add phone number");
array.add(input.next());
System.out.println("Plese add email address");
array.add(input.next());
System.out.println("Plese add last name");
String last = input.next();
lastName.put(last, array);
System.out.println("This is what you just entered: " + lastName);
System.out.println("\nWould you like to add another contact?"
+ " Type 1 for yes - 2 for no");
secondChoice = input.nextInt();
if(secondChoice == 1)
{
exit = true;
String hold = lastName.toString();
System.out.println(hold);
}
else
{
for (Map.Entry product : lastName.entrySet())
{
System.out.println(product.getKey() + " : " + product.getValue());
}
}
}
}
else
{
System.out.println("Thank you for using my program");
}
}
catch(Exception e)
{
System.out.println("Error: " + e.getMessage());
}
}
}
答案 0 :(得分:0)
我在下面添加了一些内联注释,但摘要是,每次循环while循环时,您都将实例化一个新的TreeMap。因此,每次您选择要添加其他联系人时,地图都会丢失所有先前的数据。我已经展示了TreeMap是在循环外部配置的,但是为了清楚起见,您可能希望将其在代码中上移。
涵盖的其他要点:
1)关闭扫描仪!打开扫描仪会导致内存泄漏,这是没人要的。
2)对于while循环,您没有退出条件。当前选择2只会使您回到程序的开始。
3)类型安全性-您在for-each循环中正在检查的Entry是原始类型。。我更新了代码以显式设置特定于类型的Entry。
Error: C stack usage 2011331632 is too close to the limit