英文:
return variable after for loop in a different class
问题
以下是您要翻译的内容:
我尝试在不同的类中创建一个 for 循环,并希望在主函数外部获取循环的最后一个值。问题是:无法解析 x...
我还想在不同的类中有许多值和一个 for 循环。我该如何解决这个问题?任何帮助都非常受欢迎。提前感谢您。
public class Javaapp {
public static void main(String[] args) {
Data a = new Data();
int[] getData = a.returnData();
a.for1();
System.out.println(a.x); // 无法解析 x,或者 x 不是一个字段
System.out.println(a.k);
}
}
//-------------------------------------------------
public class Data {
int k = 1;
public double for1() {
int x = 2;
for (int i = 0; i < 10; i++) {
x = x * x;
}
return x;
}
}
英文:
So i tried to create a for loop in a different class and wanted to get the last value of the loop outside to the main function. Problem is: x cannot be resolved...
I also want to have many values and a for loop in a different class. How do i fix this issue? Any help is very welcome. I thank you in advance.
public class Javaapp {
public static void main(String[] args) {
Data a = new Data();
int[] getData = a.returnData();
a.for1();
System.out.println(a.x); //x cannot be resolved or is not a field
System.out.println(a.k);
}
}
//-------------------------------------------------
public class Data {
int k=1;
public double for1() {
int x = 2;
for (int i = 0; i < 10; i++) {
x = x *x;
}
return x;
}
}
答案1
得分: 0
访问循环结束后的循环值,您需要设置类属性或捕获函数的返回值。
尝试这段代码:
public class Javaapp {
public static void main(String[] args) {
Data a = new Data();
int[] getData = a.returnData();
a.for1(); // 也可以调用: int x = a.for1();
System.out.println(a.x); //x无法解析或不是字段
System.out.println(a.k);
}
}
//-------------------------------------------------
public class Data {
public int k=1; // 可以在类外部访问
public int x=0;
public double for1() {
int x = 2;
for (int i = 0; i < 10; i++) {
x = x * x;
}
this.x = x; // 设置类属性
return x; // 返回值
}
}
英文:
To access the loop value after the loop, you need to set the class property or capture the return value from the function.
Try this code:
public class Javaapp {
public static void main(String[] args) {
Data a = new Data();
int[] getData = a.returnData();
a.for1(); // can also call: int x = a.for1();
System.out.println(a.x); //x cannot be resolved or is not a field
System.out.println(a.k);
}
}
//-------------------------------------------------
public class Data {
public int k=1; // can access outside class
public int x=0;
public double for1() {
int x = 2;
for (int i = 0; i < 10; i++) {
x = x *x;
}
this.x = x; // set class property
return x; // return value
}
}
答案2
得分: 0
尝试一下。
public class Javaapp {
public static void main(String[] args) {
Data a = new Data();
int[] getData = a.returnData();
// a.for1();
System.out.println(a.for1());
System.out.println(a.k);
}
}
英文:
Try this.
public class Javaapp {
public static void main(String[] args) {
Data a = new Data();
int[] getData = a.returnData();
// a.for1();
System.out.println(a.for1());
System.out.println(a.k);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论