java - do while string is NOT null or empty
23,228
You can use break to exit a for loop, same as you would a switch statement:
String[] wepN = new String[100];
int wepQty = 0;
for (int i=0; i < wepN.length; i++) {
if (data.getItems().get(i).getName() == null || "".equals(data.getItems().get(i).getName())) {
System.out.println(data.getItems().get(i).getName() + " -NO MOARE");
break;
}
wepN[i] = data.getItems().get(i).getName();
wepQty++;
}
Comments
-
test almost 2 years
OK so here is some logic thinking... What I am trying to do is loop through strings until I hit a null/empty string.. then STOP. All while putting those strings inside a string array...
Here is a sample of the code. I know it's wrong but hopefully to give you an idea of what I am trying to achieve:
int i; wepN = new String[100]; int wepQty = 0; boolean anyLeft = true; while (anyLeft == true) { for(i = 0;i < 100;i++) { if (data.getItems().get(i).getName() == null) { anyLeft = false; System.out.println(data.getItems().get(i).getName() + " -NO MOARE"); } wepN[i] = data.getItems().get(i).getName(); wepQty++; } }
-
Blessed Geek almost 14 years"No moare"! Was that a deliberate typo? Do you speak Maineglish? In other words, are/were you from Maine. e.g., close the doare. That's a pretty flowah.
-
test almost 14 yearsIt's meant to say "No more". Sorry for my English.
-
Gunslinger47 almost 14 yearsYou likely want to store the value of data.getItems() so you're only calling it once. It's likely to be a very expensive operation.
-
-
jayshao almost 14 yearsI wouldn't recommend jumping straight to a Collection - you could have an interface that requires String[], or have some other reason for preferring it.
-
Gunslinger47 almost 14 yearsIf it implements Iterable, it can be used in a for each loop.
-
Gunslinger47 almost 14 years
wepQty
andi
are always equal. Thus,i
is unnecessary. -
Gunslinger47 almost 14 yearsMy comment on NullUserException's answer also applies here. stackoverflow.com/questions/3296165/…
-
Gunslinger47 almost 14 yearsYou can test if a String is equal to "" by saying
str.isEmpty()
. -
jayshao almost 14 years@Gunslinger47 while you can call str.isEmpty() and in this case since we do a null check first it's safe, it's still a good habit in a lot of cases to prefer the older "".equals() since it's always null-safe and String interning means it's not really any less efficient.