尝试遍历列表

时间:2020-07-25 23:05:11

标签: java list loops android-studio

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

        }
    });

2 个答案:

答案 0 :(得分:1)

与此有关的主要问题是,在进入for循环时,myList仅包含单个元素:来自convertedCost.getText()。ToString()的30。在任何情况下,myList的铜值都不会为60。 当您通过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);

答案 1 :(得分:0)

首先,您正在重用变量名editText,因此您将无法访问它。但这无关紧要,因为您还是将其设置为空字符串。

第二,根据您的代码,editTextconvertedCost是完全相同的东西,因为您要将convertedCost添加到myList,然后从该列表中读取作为editText

第三,您没有得到后者的数字60,因为您没有将其连接到字符串。

也许这段代码可以帮助您:

copperStr = String.format("Copper %s = Silver %s", editText, convertedCost.getText().toString());

这有点像用+连接多个字符串,但是以更具可读性的方式进行