【发布时间】:2017-03-16 03:00:32
【问题描述】:
几个问题。我正在创建一个搜索元素对象数组的方法(其中每个元素对象都已使用 [atomicNumber 缩写名称 atomicWeight] 进行了初始化)。我还需要返回“对元素的引用”——不完全确定如何执行此操作。用户在 main 中输入一个缩写,然后在数组上使用 findAbbreviation 方法。 toString 方法格式化并将每个数据类型作为字符串返回。我如何在整个数组的任何给定对象中搜索缩写位置。以及如何返回对该“元素”对象的引用。
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;
}
【问题讨论】:
-
你是怎么进入这个循环的?你的情况一开始是错误的。
-
您也无法通过尝试使用字符串作为索引从数组中获取元素。你从哪里调用这个方法?您将不得不使用循环查找字符串并在搜索时跟踪索引。如果您想要 abbreviationP 的索引,那么您需要使用 for 循环并搜索数组,直到找到它。在那一刻,您拥有找到它的索引。