2014-10-03 60 views
-2
  1. 使用ArrayList类的toString方法打印ArrayList。
  2. 询问用户名称以从列表中删除。如果在列表中找不到该名称,请打印一条消息,指出该名称不在列表中。如果找到了,请删除名称,然后打印当前列表。

我似乎无法得到toString方法的工作,也没有“如果找到列表,删除名称,并打印当前列表”。Java 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(); 
} 
+0

定义“我不能”。你期望代码做什么,它做什么呢? – 2014-10-03 07:04:01

+0

“找不到符号 - 变量列表”toString(),我不知道如何去通过toString()返回列表。 – Bob 2014-10-03 07:13:27

+0

错误的行号是什么?该行有没有可用的列表?线路变量在哪里定义?你真的认为方法中定义的变量可用于任何其他方法吗?按照问题,主要方法的代码已经使用了ArrayList的toString()方法。我不确定你为什么要在你的类中定义一个toString()方法。 – 2014-10-03 07:14:41

回答

0

对于delete部分

尝试

if (list.contains (deleteName)) 
{ 
    list.remove (deleteName); 
} 

这是没有必要遍历。

此外,为使listtoString方法可见,请将其设置为类字段。

0

我看到的第一个问题是你的列表不是全局的,所以你的toString()没有任何访问权限。

至于删除的情况下,我看起来很好。