【发布时间】:2014-10-03 06:54:21
【问题描述】:
- 使用 ArrayList 类的 toString 方法打印 ArrayList。
- 询问用户要从列表中删除的名称。如果在列表中找不到该名称,则打印一条消息,说明该名称不在列表中。如果找到,请删除名称,然后打印当前列表。
我似乎无法让 toString 方法工作,也无法让“如果找到列表,删除名称并打印当前列表”。
public static void main(String[] args) throws IOException
{
ArrayList<String> list = new ArrayList<String>();
// Open the file
File file = new File("input.txt");
Scanner inputFile = new Scanner(file);
// Read until the end of the file
while(inputFile.hasNext()){
//String str = inputFile.nextLine();
list.add(inputFile.next());
System.out.println(list.toString() + " " + list.size());
}
inputFile.close();
// Add a name to the end of the list
list.add("Michael");
System.out.println("\nMichael is added to the end of the list: \n" + list.toString());
// Add a name to the list in position 2
list.add(2, "Lucy");
System.out.println("\nLucy is added to the list as the third name: \n" + list.toString());
// Find the indexOf Michael
System.out.println("\nindexOf Michael is: " + list.indexOf("Michael"));
// Replace Michael with Mike
list.set(11, "Mike");
System.out.println("\nReplace Michael with Mike: \n" + list.toString());
// Ask user for a name to delete from the list
Scanner input = new Scanner(System.in);
System.out.print("What name would you like to delete from the list? ");
String deleteName = input.nextLine();
// If name not found then display message
boolean found = false;
if(found == false)
System.out.println("The name is not on the list");
// If name found then delete name and show current ArrayList
for(String a: list){
if(a.compareTo(deleteName) == 0){
list.remove(a);
System.out.println(a + " was deleted from the list. Here is the new list: \n" +
list.toString());
}
}
// String str = (String)nameList.get(0);
}
// Use toString method of the ArrayList Class.
public String toString()
{
return list.toString();
}
【问题讨论】:
-
定义“我不能”。您希望代码做什么,它会做什么?
-
“找不到符号 - 变量列表”用于 toString(),而且我不确定如何通过 toString() 返回列表。
-
错误的行号是多少?该行是否有可用的变量列表? line 变量在哪里定义?您真的认为方法中定义的变量可用于任何其他方法吗?如所要求的,main 方法的代码已经使用了 ArrayList 的 toString() 方法。我不确定你为什么要在你的类中定义一个 toString() 方法。
标签: java arrays eclipse arraylist tostring