java - 尝试遍历列表
问题描述
我试图制作一个迭代列表,它将文本设置为“Copper 60 = Silver 30”所以“Copper”和“Silver”是字符串,然后 60 来自 editText,30 来自转换后的成本。目前它正在显示“Copper 30 = Silver”所以它以错误的方式显示它并且没有添加来自 ediText 的 60。有人可以帮助我坚持了几个小时。这是我的代码:
myList.add(convertedCost.getText().toString());
editText.getText();
editText.setText("");
String copperStr = "Copper";
String silverStr = "Silver";
for(String editText : myList){
copperStr = copperStr + " " + editText + " = " + silverStr;
}
txtList.setText(copperStr);
}
});
解决方案
这样做的主要问题是,当您进入 for 循环时,myList 仅包含一个元素:30,来自 convertCost.getText().ToString()。铜价值的 60 绝不会添加到 myList。当您通过 for 循环时,editText 被分配给 myList 中的下一个元素,从第一个元素开始。myList 中唯一的元素是 30,表示在第一个循环中,变量如下:
myList is ["30"]
editText is myList[0] is "30"
copperStr is "Copper"
silverStr is "Silver"
因此,当您完成第一个循环时,会将以下内容分配给 CopperStr:
copperStr = copperStr + " " + editText + " = " + silverStr
copperStr = "Copper" + " " + "30" + " = " + "Silver"
copperStr = "Copper 30 = Silver"
但是,如果您在列表中插入“60”,在插入“30”之前,那么第一个循环将设置以下变量
myList is ["60", "30"]
editText is myList[0] is "60"
copperStr is "Copper"
silverStr is "Silver"
第一个循环将产生以下内容:
copperStr = copperStr + " " + editText + " = " + silverStr
copperStr = "Copper" + " " + "60 + " = " + "Silver"
copperStr = "Copper 60 = Silver"
然后到第二个循环,变量如下:
myList is ["60", "30"]
editText is myList[1] is "30"
copperStr is "Copper 60 is Silver"
silverStr is "Silver"
第二个循环将产生以下结果:
copperStr = copperStr + " " + editText + " = " + silverStr
copperStr = "Copper 60 = Silver" + " " + "30" + " = " + "Silver"
copperStr = "Copper 60 = Silver 30 Silver"
这也不是你想要的
相反,您可能希望类似于以下内容
myList.add("60");
myList.add(convertedCost.getText().toString());
editText.getText();
editText.setText("");
String copperStr = "Copper";
String silverStr = "Silver";
editText.setText(copperStr + " " + myList[0] + " = " + myList[1] + " " + silverStr);
txtList.setText(editText);
推荐阅读
- regex - 在 postgresql 中清理字符串
- embedded - ESP-IDF || 核心转储
- python - 将 random.random 均匀转换为指数分布不会产生正确的结果
- mongoose - Mongoose `$project` 如何避免重复文件
- c# - 如何自定义输出serilog
- transactions - 我们可以为 Atomikos JTA 属性中的某些属性设置值,并为其他属性获取 jta.properties 中指定的默认值吗?
- json - 在 Swift 中将 JSON 对象解码为纯字符串
- node.js - Node.JS 应用程序 CPU 使用率越来越高
- mysql - 一个 VIEW 的左 JOIN 与一个包含多个列的巨大表花费了太多时间
- java - maven 可以在编译而不是运行时抛出错误吗?