简体   繁体   中英

how to initialize variable with iterator inside a loop in java?

Is it possible to initialize variable with iterator inside a loop?

Example:

For (int i =0 ; i<3; i++){

String var[i] = "Something"+i;

}

System.out.print(var1);
System.out.print(var2);
System.out.print(var3);

Output:

"Something1"
"Something2"
"Something3"

You have to work a lot on your basics, buddy. The code above is messed up. Still, I will help you with the working code for this use case.

To answer to your question. Yes, it is possible to initialise variable with iterator inside loop. You can do it as follows:

String var[] = new String[3];

for(int i =0 ; i<3; i++){
    var[i] = "Something"+i;
}

System.out.print(var[1]);
System.out.print(var[2]);
System.out.print(var[3]);

I kept it simple for you to understand. Do read the comments below for better-optimized code. Happy coding!

I didn't mean it like an array. I literally mean a new String variable. Like Var1, Var2 & Var3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM