gpt4 book ai didi

java - indexOf() 方法在 ArrayList 中找不到我的字符串

转载 作者:行者123 更新时间:2023-11-30 07:52:25 27 4
gpt4 key购买 nike

我是 Java 的新手,我正在尝试编写一些简单的代码来查找在组合框中选择的对象(溶剂),然后在按下名为 shift 的按钮时显示与其关联的数字(shift 值)形式。

我已将其设置为包含溶剂及其相应位移值的数组。我将组合框对象转换为字符串,将其存储为字符串“已选择”,然后尝试检查此“已选择”字符串在数组中的位置。为此,我将数组转换为 ArrayList 并使用了 indexOf

这段代码抛出一个 ArrayIndexOutOfBoundsException 因为 int position 总是以 -1 出现,所以当我尝试将显示文本设置为 solvents[position] [1] 结果显示为 solvents[-1][1],但不起作用。

我的问题是为什么会出现 -1?我知道这意味着在列表中找不到字符串,但它应该是。 (即列表应如下所示:CDCl3、H2O ... 等。因此 String“选择的”"CDCl3" 在该列表中。)

此外,即使这确实有效并且 position = -1 没有出现,我知道我的下一行 textDisplay.setText(solvents[position][1]) ; 必须修改,因为现在位置指的是 ArrayList 中的位置,而不是数组中的位置。有人有什么想法吗?谢谢。

String[][] solvents = new String[4][2];
String chosen;

public void populate_array() {
solvents[0][0] = "CDCl3";
solvents[1][0] = "H2O";
solvents[2][0] = "CD2Cl2";
solvents[3][0] = "DMSO";
solvents[0][1] = "7.26";
solvents[1][1] = "4.79";
solvents[2][1] = "5.32";
solvents[3][1] = "2.50";
}

public int solvent_position() { // finding where in the array the solvent is
int col_length = solvents[0].length;
int row_length = solvents.length;
int i = 0;
int position = -1;
int j = 0;

populate_array();

for (i = 0; i < row_length; i++) { // go through each row to find the solvent
if (solvents[i][0].contains(chosen)) {
position = Arrays.asList(solvents).indexOf(chosen);
textDisplay.setText(solvents[position][1]); // trying to the display the number associated with the solvent
}
}
return position;
}

private void shift_buttonActionPerformed(java.awt.event.ActionEvent evt) {
chosen = (String) combo_solvent.getSelectedItem();
solvent_position();
}

最佳答案

我建议您重写代码以使用映射,这将大大简化您的代码,并且您不需要处理所有索引或手动查找所选溶剂。

看来你对shift值感兴趣,而不是具体的位置,获取shift值就像下面的例子一样。

我对这两个值都使用了字符串,但您可以对移位值使用 float 。

//Create the map with the values
HashMap<String, String> solvents = new HashMap<String, String>();

//Populate the data in your map
solvents.put("CDCl3", "7.26");
solvents.put("H2O", "4.79");

//Obtain the shift value, null if the element wasn't found
String shiftvalue = solvents.get(chosen);

关于java - indexOf() 方法在 ArrayList 中找不到我的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45906418/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com