2013-03-03 96 views
1

我正在通過Java中的對象優先(用於在測試前進行檢查)練習。一個練習要求我創建一個checkIndex方法,我已經正確地完成了。下一部分要求我重寫我的listFile和removeFile方法,以便它們使用我的checkIndex方法確保輸入了有效的參數。我不知道如何做到這一點,並嘗試了一些事情。一些幫助將不勝感激。謝謝。在練習中遇到麻煩,要求我檢查一個值

public class MusicOrganizer 
{ 
// An ArrayList for storing the file names of music files. 
private ArrayList<String> files; 

/** 
* Create a MusicOrganizer 
*/ 
public MusicOrganizer() 
{ 
    files = new ArrayList<String>(); 
} 

/** 
* Add a file to the collection. 
* @param filename The file to be added. 
*/ 
public void addFile(String filename) 
{ 
    files.add(filename); 
} 

/** 
* Return the number of files in the collection. 
* @return The number of files in the collection. 
*/ 
public int getNumberOfFiles() 
{ 
    return files.size(); 
} 

/** 
* List a file from the collection. 
* @param index The index of the file to be listed. 
*/ 
public void listFile(int index) 
{ 
     String filename = files.get(index);  //not sure 
     System.out.println(filename); 
    } 




/** 
* Remove a file from the collection. 
* @param index The index of the file to be removed. 
*/ 
public void removeFile(int index) 
{ 
    if(index >= 0 && index < files.size()-1) { 
     files.remove(index); 
    } 
} 

public String getfive(){ 
    return files.get(4); 
} 

public void addNew(String whatIsYourFavourite){ 
    files.add(whatIsYourFavourite); 
} 

public void remove(){ 
    files.remove(2); 
} 

public void checkIndex(int check){ 
    if ((check >= 0) && (check <= files.size()-1)){ 

    } 
    else{ 
     System.out.println("Valid range must be between 0 and -1"); 
    } 

} 

public boolean checkIndex2(int check2){ 
    if ((check2 >= 0) && (check2 <= files.size()-1)){ 
     return true; 
    } 
    else{ 
     return false; 
    } 

} 
} 
+0

爲什麼這麼複雜? check2 <= files.size() - 1 這也是一樣的:check2 Holly 2013-03-03 09:06:20

回答

2

其實這應該是比較容易的。假設你的代碼對於刪除和檢查索引是正確的,你可以使用checkindex2在if語句中返回一個布爾值。所以,你必須

public void removeFile(int index) 
    { 
     if(checkindex2(index)) 
{ 
      files.remove(index); 
     } 
    } 

和列表

public void listFile(int index) 
     { 
       if(checkindex2(index)){ 
       System.out.println(files.get(index)); 
      } 
}