+ 2

Is it possible to create a loop in java using a String not an Integer(int) and how it it done?

4th Jun 2019, 2:18 PM
NavasJosh
NavasJosh - avatar
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
4th Jun 2019, 2:40 PM
Yusuf
Yusuf - avatar
+ 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..
4th Jun 2019, 2:46 PM
JavaBobbo
JavaBobbo - avatar
+ 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
4th Jun 2019, 2:48 PM
Yusuf
Yusuf - avatar
+ 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
4th Jun 2019, 3:00 PM
JavaBobbo
JavaBobbo - avatar
+ 1
Possibly something like this: String s = "0"; while (!s.equals("10")) { System.out.println(s); s = s.valueOf(Integer.valueOf(s)+1); }
4th Jun 2019, 3:22 PM
Cluck'n'Coder
Cluck'n'Coder - avatar
+ 1
JavaBobbo it was not my question I was answering
4th Jun 2019, 4:02 PM
Yusuf
Yusuf - avatar
+ 1
Cluck'n'Coder that's a while loop not a for loop
4th Jun 2019, 4:03 PM
Yusuf
Yusuf - avatar
+ 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);
4th Jun 2019, 4:58 PM
Cluck'n'Coder
Cluck'n'Coder - avatar
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
4th Jun 2019, 2:50 PM
Roel
Roel - avatar
0
You can use map ( Map<String,Object>) instead so keyset will be string set you can iterate through it.
4th Jun 2019, 5:47 PM
Sharofiddin
Sharofiddin - avatar