+ 2
Is it possible to create a loop in java using a String not an Integer(int) and how it it done?
11 Answers
+ 2
No.
As far as for loops go you must define an integer to indicate how many times the process is.supposed to repeat
+ 1
Yes you can. You can create an String array for example:
String[] names = {"Name1","Name2","Name3"};
for(String n: names)
System.out.println(n);
If it is what you mean..
+ 1
JavaBobbo that's still using the number of names in the array names you can also call a function to get the number of entries in an array
so technically you still have to use an integer
+ 1
Roel Yesbox but still an String đ
Yusuf then I think you should rephrase your question so that people can understand better..
For me it sounds you wanna use a String in a loop instead of int
+ 1
Possibly something like this:
String s = "0";
while (!s.equals("10")) {
System.out.println(s);
s = s.valueOf(Integer.valueOf(s)+1);
}
+ 1
JavaBobbo it was not my question I was answering
+ 1
Cluck'n'Coder that's a while loop not a for loop
+ 1
@Yusuf - The questioner never explicitly stated that he wanted a for-loop - just a loop using a string. But assuming a for-loop was requested:
for (String s = "0"; !s.equals("10"); s = s.valueOf(Integer.valueOf(s)+1))
System.out.println(s);
0
JavaBobbo that's an array, but fair enough. Another way is using length. I don't know how java does that, but in js you can use
for(int i=0; i<anystring.length; i++){ /// code goes here /// }
Where anystring is a string or a variable holding a string, but yes, .length returns an integet
0
You can use map ( Map<String,Object>) instead so keyset will be string set you can iterate through it.