用户输入while循环在Java中</p> <pre><code>5 </code></pre> <p>需要的输出(使用while循环)不工作
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
代码嵌套形成这个数字,但我不能..请帮助
用户输入while循环在Java中</p> <pre><code>5 </code></pre> <p>需要的输出(使用while循环)不工作
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
代码嵌套形成这个数字,但我不能..请帮助
temp2
内部值while
循环的值将为a+1
。由于您以后未将其重置为1
,因此将不会再次输入此内部循环,因为条件while(temp2<=a)
不会被满足。要纠正它,请在内循环之前或之后将temp2
设置为1
。
谢谢先生..它的工作 –
@ArkaBhattacharjee没问题:)很高兴我能帮上忙。 – Pshemo
下面的代码注释说明了代码的错误。
//assume temp1 equals 1
while(temp1 <= a){
temp2 = 1;//you're primarily forgetting to reset the temp2 count
while(temp2 <= a){
temp = temp1*temp2;
System.out.print(temp + " ");
temp2++;
}
temp1++;
System.out.println();
}
int a = 5;
int temp1 = 1;
int temp2= 1;
int temp = 1;
while(temp1 <= a){
while(temp2 <= a){
temp = temp2*temp1;
System.out.print(temp + " ");
temp2++;
}
System.out.println();
temp1++;
temp2=1;
}
上面的代码应该有你想要的结果。在循环结束时重置temp2变量。只需将int a = 5
更改为任何你想要的。
附加应答:
int userInput = 5;
int answer = 0;
for(int y = 0; y < userInput; y++){
for(int x = 0; x < userInput; x++){
answer = x * y;
System.out.print(answer + " ");
}
System.out.println();
}
有了这个答案,你不需要重新设置临时变量,会产生预期的效果
如果我要打破这个问题转化为简单的话,
有n种方法可以做到这一点。
我想使用for循环将是最简单的。
int a = 5; //Or however else you get this value.
//Initialize your values
int temp1 = 1;
int temp2 = 1;
int temp; //Only need a declaration here.
while (temp1 <= a) {
while(temp2 <= a) {
temp = temp1*temp2;
System.out.print(temp + " ");
temp1++;
temp2++;
}
//This executes between inner loops
temp2 = 1; //It's important to reset
System.out.println();
}
或者另一种紧凑的方式:
int a = 5;
int row = 0;
int col = 0;
while (++row <= a) {
while(++col <= a) {
System.out.print(row*col + " ");
}
col = 0;
System.out.println();
}
for(int i=1; i<=a; i++){
System.out.print(i);
for(int j=2; j<=a; j++){
int val = i*j;
System.out.print(" " + val);
}
System.out.println();
}
它是如何不工作?输出是否错误? – thegrinner
请发布整个功能,这只是它的一部分。 即你正在给temp分配东西,但是temp没有声明 – bwawok
你为什么不使用for循环?或者你的调试器来调试你的代码?我怀疑'temp2'应该被重置为1。 –