【发布时间】:2014-04-01 19:47:29
【问题描述】:
我设法在我的数组中动态添加一个元素,但不幸的是程序停止了。我该如何继续?谢谢!
....
List<String> messages = Arrays.asList("Mary", "Nadia!", "Drake");
System.out.println("Enter Costumer's Name:");
cust_name =in.next();
if(cust_name .equals("Mary"))
System.out.println("Already a member!");
else if (cust_name .equals("Nadia"))
System.out.println("Already a member!");
else if(cust_name .equals("Drake"))
System.out.println("Already a member!");
else
messages.add(in.next());
System.out.println("Not a member! " + cust_name + " just added.");
....
【问题讨论】:
-
当你的程序停止时,它应该告诉你出了什么问题。将有描述和堆栈跟踪的异常。请发布错误。
-
需要stacktrace,而不是检查每个元素的硬编码,你应该检查
if(messages.contains(cust_name)) -
另一种方法是使用
Set<String>(例如HashSet)来存储名称。当您向Set添加内容时,返回的值为boolean,它告诉您该值是否实际上是新的——您可以根据该值打印适当的消息。它会让你的代码更短更干净。
标签: java arrays element add continue