问题
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