[英]Calling a method from within another method of the same class
我有許多方法需要實現我的add方法,但是我不確定如何執行此操作,因為所有方法都在同一類ArrayPhoneDirectory中。
添加方法:
private void add(String name, String telno) {
if (size >= capacity)
{
reallocate();
}
theDirectory[size] = new DirectoryEntry(name, telno);
size = size +1;
}
以下是需要調用add的方法:
加載:
public void loadData(String sourceName) {
Scanner scan = new Scanner(sourceName).useDelimiter("\\Z");
while (scan.hasNextLine()) {
String name = scan.nextLine();
String telno = scan.nextLine();
DirectoryEntry newdir = new DirectoryEntry(name, telno);
//ADD THE NEW ENTRY TO THE DIRECTORY
}
}
addChangeEntry:
public String addChangeEntry(String name, String telno) {
for (DirectoryEntry x : theDirectory) {
if (x.getName().equals(name)) {
x.setNumber(telno);
return x.getNumber();
} else {
// add a new entry to theDirectory using method add
}
}
return null;
}
這可能很明顯,但是我對Java還是很陌生,因此對於如何調用這些方法的任何幫助將不勝感激!
您可以只調用add(name, telno)
,它將起作用。
實際上,您的add
方法是私有的,因此只能從類內部調用。
例如,在您的加載方法中:
public void loadData(String sourceName) {
Scanner scan = new Scanner(sourceName).useDelimiter("\\Z");
while (scan.hasNextLine()) {
String name = scan.nextLine();
String telno = scan.nextLine();
// You don't need this, add builds its own DirectoryEntry from name and telno
// DirectoryEntry newdir = new DirectoryEntry(name, telno);
add(name, telno);
}
}
您可以在addChangeEntry
做完全一樣的事情
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.