简体   繁体   English

如何在 java 的循环中用迭代器初始化变量?

[英]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: 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.我的意思是一个新的 String 变量。 Like Var1, Var2 & Var3像 Var1、Var2 和 Var3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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