2012-06-15 45 views
0

在我創建的程序中,用戶將輸入值以創建視頻陣列。每個視頻包含多個數據字段(編號,標題,出版商,時長&日期)。然而,我目前試圖達到的目標是讓用戶在他們剛剛創建的數組中選擇一個特定視頻,選擇他們希望重命名的數據字段,重命名該值,然後將重命名值設置爲新值。這裏是我的添加視頻到一個數組代碼:Java陣列:通過用戶輸入選擇和替換值

public Library createLibrary() 
{ 
    Library video = new Library(); 
    java.util.Scanner scannerObject =new java.util.Scanner(System.in); 
    for (int i = 0; i < videos.length; i++) 
    { 
    //User enters values into set methods within the Library class 
    System.out.print("Enter video number: " + (i+1) + "\n"); 
    String number = scannerObject.nextLine(); 
    System.out.print("Enter video title: " + (i+1) + "\n"); 
    String title = scannerObject.nextLine(); 
    System.out.print("Enter video publisher: " + (i+1) + "\n"); 
    String publisher = scannerObject.nextLine(); 
    System.out.print("Enter video duration: " + (i+1) + "\n"); 
    String duration = scannerObject.nextLine(); 
    System.out.print("Enter video date: " + (i+1) + "\n"); 
    String date= scannerObject.nextLine(); 
    System.out.print("VIDEO " + (i+1) + " ENTRY ADDED " + "\n \n"); 
    //Initialize arrays 
    videos[i] = new Library(); 
    videos[i].setVideo(number, title, publisher, duration, date ); 
    } 
    return video; 
} 

,這裏是爲我的那些選擇和替換功能的基本概念,誰也弄不清我的意思:

public void replaceVideo(Library[] videos, String replaceTo, String replaceWith) 
    { 
    for (int i = 0; i < videos.length; i++) 
     if (videos[i].equals(replaceTo)) { 
      videos[i]= replaceWith; 
     } 
    } 

簡單解決方案將不勝感激。謝謝。

回答

0

嘗試比較replaceTo到視頻的名稱(或任何replaceTo應該匹配):

if (videos[i].getName().equals(replaceTo)) { 
0

我看不到你的替換工作,因爲它看起來像是比較庫類型和字符串類型與.equals()。

如果您使用的集合類代替陣列中的一個,替換方法的變化

public void replaceVideo(Vector<Library> videos, Library current, Library newCopy) 
{ 
    Collections.replaceAll(videos, current, newCopy); 
} 

我用向量,但是可以在需要時可以使用集,列表等。

0

爲了讓您的代碼正常工作,您需要重寫Library.equals方法來僅比較字符串。否則,您可以將一個樣本的視頻標題與參數replaceTo進行比較。

當然,重寫equals方法是OOP的優雅。試試我的建議和托馬斯'

祝你好運。