将值从内部 while 循环传递到不同的 class
Passing value from inside while loop to different class
假设我有一个带有 while 循环的主 class:
public class Main {
public static void main(String[] args) throws InterruptedException {
int one = 1;
int counter = 0;
while (one<100){
Thread.sleep(1000);
counter += 1;
Function.Move();
one++;
}
此循环中的计数器变量正在对流逝的每一秒进行计数。
有一个单独的 class 函数:
public class Function {
public static int Move (int result){
result = 1 + counter;
return result;
}
}
所以正如你所看到的,在函数 class 的 Move 方法中,我希望能够使用计数器变量的新值,它随着每一秒的流逝而增加,来计算 a 的值不同的变量,然后将返回到 main 方法。
问题是一开始我不知道如何将计数器的值传递给函数 class 中的 Move 方法。
我不确定我是否正确理解你想做什么,这取决于你稍后需要那个结果变量的确切位置我认为你的代码应该看起来像这样:
public class Main {
int counter;
public static void main(String[] args) throws InterruptedException {
int one = 1;
counter = 0;
while (one<100){
Thread.sleep(1000);
counter += 1;
one++;
}
}
public int getCounter() {
return counter;
}
}
public class Function {
public static int move (int result, Main main){
result = 1 + main.getCounter();
return result;
}
}
您现在可以在程序中任何需要它的地方使用 Function.move()。
但是,请注意,您需要在与主线程不同的线程中使用 Function.move() 到 运行 的代码。否则它总是 return 101 或 1,因为 while 循环在你调用 Function.move() 之前或之后总是 运行ning,这取决于你在哪里调用它(除非你从 while 循环中调用它,但是你可以只使用 counter++ 而不需要额外的 class)
假设我有一个带有 while 循环的主 class:
public class Main {
public static void main(String[] args) throws InterruptedException {
int one = 1;
int counter = 0;
while (one<100){
Thread.sleep(1000);
counter += 1;
Function.Move();
one++;
}
此循环中的计数器变量正在对流逝的每一秒进行计数。
有一个单独的 class 函数:
public class Function {
public static int Move (int result){
result = 1 + counter;
return result;
}
}
所以正如你所看到的,在函数 class 的 Move 方法中,我希望能够使用计数器变量的新值,它随着每一秒的流逝而增加,来计算 a 的值不同的变量,然后将返回到 main 方法。
问题是一开始我不知道如何将计数器的值传递给函数 class 中的 Move 方法。
我不确定我是否正确理解你想做什么,这取决于你稍后需要那个结果变量的确切位置我认为你的代码应该看起来像这样:
public class Main {
int counter;
public static void main(String[] args) throws InterruptedException {
int one = 1;
counter = 0;
while (one<100){
Thread.sleep(1000);
counter += 1;
one++;
}
}
public int getCounter() {
return counter;
}
}
public class Function {
public static int move (int result, Main main){
result = 1 + main.getCounter();
return result;
}
}
您现在可以在程序中任何需要它的地方使用 Function.move()。
但是,请注意,您需要在与主线程不同的线程中使用 Function.move() 到 运行 的代码。否则它总是 return 101 或 1,因为 while 循环在你调用 Function.move() 之前或之后总是 运行ning,这取决于你在哪里调用它(除非你从 while 循环中调用它,但是你可以只使用 counter++ 而不需要额外的 class)