Reputation: 5121
Hi so lately I've been doing a lot of java programming and I've been using a lot of if statements. the problem is i have to copy and paste the if statements over a hundred times to check all the senarios. Here is an example:
while (i < AreaNumbers.size()) {
String roomnum = "j" + AreaNumbers.get(i);
if (roomnum.equals("j100")) {
if (k == 1) {
j100.setVisible(true);
j100.setToolTipText("<html>" + "<br>" + "Room Number: " + AreaNumbers.get(i) + "<br>" + "Incident ID: " + IncidentID.get(i) + "<br>" + " Teacher: " + Teachers.get(i) + "<br>" + " Description: " + Descriptions.get(i) + "</html>");
k = k + 1;
} else if (k > 0) {
j100.setToolTipText(k + " help desk calls, click here for more information");
k = k + 1;
}
for this example i would copy and paste the if (roomnum.equals("j100")) {
and everything past it for every label i want to check and compare. Is there anyway i could do this where i could write a statement that goes through this same scenario once and everywhere it sees j100
it could replace it after each time with a different label, such as j101 j107 an so on. Im sorry if this isnt very clear i just cant think of a better way to word it. Thanks in advance.
Upvotes: 1
Views: 659
Reputation: 272457
Don't use numbered variable names (like j100
, j101
, etc.). Use an array instead, so you can loop over them programatically:
SomeType[] j = new SomeType[1000];
for (int z = 0; z < j.length; z++) {
j[z] = new SomeType();
j[z].setTooltipText("Hello world");
}
Depending on what you need to do, you may want to investigate the more advanced collections classes instead of simple arrays.
Upvotes: 9
Reputation: 12901
you could use a Map<String, Runnable>
using the label as the key and to a Runnable
. Depending on how you write you Runnable subclasses, this could alleviate a lot of redundancy.
if( myMap.containsKey( myLabel ) ) {
myMap.get(myLabel).run();
}
Upvotes: 0