Inserting a variable amidst another variable

試著忘記壹切 提交于 2020-01-04 07:52:15

问题


I have three textboxes ct1,ct2,ct3. I have to use a for loop 1 to 3 and check whether the textboxes are empty. So, inside the for loop, how do I represent it? For example,

for(i=0;i<=3;i++)
{
    if(ct+i.getText()) // I know I'm wrong
     {
     }

}

回答1:


I have three textboxes ct1,ct2,ct3.

There's your problem to start with. Instead of using three separate variables, create an array or collection:

TextBox[] textBoxes = new TextBox[3];
// Populate the array...

Or:

List<TextBox> textBoxes = new ArrayList<TextBox>();
// Populate the list...

Then in your loop:

// Note the < here - not <=
for (int i = 0; i < 3; i++) {
   // If you're using the array
   String text = textBoxes[i].getText();

   // or for the list...
   String text = textBoxes.get(i).getText();
}

Or if you don't need the index:

for (TextBox textBox : textBoxes) {
    String text = textBox.getText();
    ...
}



回答2:


Use an array

TextBox[] boxes = new TextBox[]{ct1,ct2,ct3};
for(i=0;i<3;i++)
{
    boxes[i].getText(""); // I know I'm wrong
}



回答3:


You can put your text boxes in a list and iterate over that list:

List<TextBox> ctList = new ArrayList<TextBox> ();
list.add(ct1);
list.add(ct2);
list.add(ct3);

for (TextBox ct : ctList) {
    if(ct.getText().equals("expected text")) {
        // do your stuff here
    }
}


来源:https://stackoverflow.com/questions/11775768/inserting-a-variable-amidst-another-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!