首页 > 解决方案 > 尝试遍历列表

问题描述

我试图制作一个迭代列表,它将文本设置为“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);

        }
    });

标签: javalistloopsandroid-studio

解决方案


这样做的主要问题是,当您进入 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);

推荐阅读