4 回答
TA贡献1712条经验 获得超3个赞
你必须纠正你的while循环,因为在它的当前状态下,它不会做任何事情。
这是对您的代码的更正,它基本上可以工作(我不知道所需的输出,但看起来不错):
public static void main(String[] args) {
int sumaA = 1000;
int sumaB = 0;
Random rand = new Random();
int n = rand.nextInt(9);
int g = rand.nextInt(49);
int runCounter = 0;
while (sumaA > sumaB) {
runCounter++;
System.out.println("Loop run number " + runCounter);
System.out.println("Random N = " + n);
sumaA += n;
System.out.println("sumaA: " + sumaA);
System.out.println();
System.out.println("Random N= " + g);
sumaB += g;
System.out.println("sumaB: " + sumaB);
}
System.out.println("loop ran " + runCounter + " times");
System.out.println("value sumaA" + sumaA + "value sumaB " + sumaB);
}
请看一下循环现在的样子。每次循环运行要执行一次的所有内容都必须在循环主体内(大括号)。
TA贡献1811条经验 获得超5个赞
do {
int n = rand.nextInt(9);
int g = rand.nextInt(49);
System.out.println("Random N= "+ n);
sumaA += n;
System.out.println("sumaA: "+sumaA);
System.out.println();
System.out.println("Random N= "+ g);
sumaB += g;
System.out.println("sumaB: "+sumaB);
System.out.println("loop runs numbers");
System.out.println("value sumaA" + sumaA + "value sumaB " + sumaB);
} while (sumaA>sumaB);
}
你好,这是你想做的吗?
TA贡献1878条经验 获得超4个赞
您必须正确构造您的 while 循环并获取局部变量 counter 并将其初始化为 0。而 while 迭代在 counter 变量中添加 +1。请考虑以下代码:
public static void main( String[] args )
{
int sumaA = 1000;
int sumaB = 0;
int counter = 0;
Random rand = new Random();
int n = rand.nextInt( 9 );
int g = rand.nextInt( 49 );
while ( sumaA > sumaB )
{
System.out.println( "Random N= " + n );
sumaA += n;
System.out.println( "sumaA: " + sumaA );
System.out.println();
System.out.println( "Random N= " + g );
sumaB += g;
System.out.println( "sumaB: " + sumaB );
counter++;
}
System.out.println( "loop runs numbers " + counter );
System.out.println( "value sumaA " + sumaA + "value sumaB " + sumaB );
}
TA贡献1862条经验 获得超6个赞
while 循环括号内的代码,直到括号内的条件为假。因此,例如这段代码:
int i = 0;
loops = 0
while(i < 6){
loops++;
System.out.println("loop runs numbers"+loops);
i+=2;
System.out.println("i: "+i);
}
输出:
循环运行数字 1
我:2
循环运行数字 2
我:4
循环运行数字 3
我:6
然后因为 i 不小于 6 而停止。
现在您的代码的问题是您的 while 括号内没有任何指令,因此括号内的条件以 true 开始,并且永远不会变为 false,因为您没有在循环内更改任何内容。您应该做的是将代码移动到 while 括号内,如果您希望计算循环运行次数,请添加一个“循环”变量。最终代码应如下所示:
import java.util.*;
class Sum {
public static void main(String[] args) {
int sumaA = 1000;
int sumaB = 0;
int loops = 0;
while (sumaA>sumaB){
Random rand = new Random();
int n = rand.nextInt(9);
int g = rand.nextInt(49);{
System.out.println("Random N= "+ n);
sumaA += n;
System.out.println("sumaA: "+sumaA);
System.out.println();
System.out.println("Random N= "+ g);
sumaB += g;
System.out.println("sumaB: "+sumaB);
loops++;
System.out.println("loop runs numbers"+loops);
System.out.println("value sumaA" + sumaA + "value sumaB " + sumaB);
}
}
}
添加回答
举报