2014-10-03 58 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()沒有任何訪問權限。

至於刪除的情況下,我看起來很好。