有幾個問題。我創建了一個方法來搜索元素對象數組(每個元素對象已經用[atomicNumber縮寫名稱atomicWeight]初始化)。我還需要返回'對元素的引用' - 不完全確定如何執行此操作。用戶在main中輸入縮寫,然後在數組上使用findAbbreviation方法。 toString方法格式化並以String形式返回每個數據類型。我如何搜索整個數組的任何給定對象中的縮寫位置。我該如何返回對該「元素」對象的引用。如何搜索字符串數組中的特定單詞位置
public class PeriodicTable {
private final int MAX_ELEMENTS = 200;
private PeriodicElement[] table;
private int actualSize;
public PeriodicTable() throws IOException{
table = new PeriodicElement[MAX_ELEMENTS];
Scanner input = new Scanner(new File("file name here"));
int index = 0;
while(input.hasNext() && index < MAX_ELEMENTS) {
int aN = input.nextInt();
String abbr = input.next();
String name = input.next();
double aW = input.nextDouble();
table[index] = new PeriodicElement(aN, abbr, name, aW);
index++;
}
input.close();
actualSize = index;
}
public String findAbbreviation(String abbreviationP){
boolean found = false;
int index = 0;
while(found && index < MAX_ELEMENTS){
if (table[index] = table[abbreviationP]){
found = true;
return table[index].toString;
}
index++;
}
return null;
}
}
class PeriodicElement {
private int atomicNumber;
private String abbreviation, name;
private double atomicWeight;
public PeriodicElement(int atomicNumberP,
String abbreviationP, String nameP,
double atomicWeightP){
atomicNumber = atomicNumberP;
abbreviation = abbreviationP;
name = nameP;
atomicWeight = atomicWeightP;
}
你是如何不斷進入這個循環?你的狀況開始是錯誤的。 –
您也無法通過嘗試爲索引使用字符串來獲取數組中的元素。你從哪裏調用這個方法?您將不得不在循環中查找字符串並在搜索時跟蹤索引。如果你想索引縮寫P,那麼你需要使用for循環並搜索數組,直到找到它。在那一刻,你有了你找到的索引。 –