好的,我正在做一个程序,它可以画垂直线,水平线,对角线!我对其中一个没有任何意义的输出感到困惑。
所以我的伪代码是这样的:
//enter a char
//enter a number that will determine how long the line is
//define with easyreader what type of line it will be (hori, vert, diag)
//the idea of making the diag lines was this...
@
(two spaces) @
(four spaces) @
(six spaces) @
//we could use the sum spaces = spaces + 2; to keep on calculating what
//the previous spaces was代码是:
class starter {
public static void main(String args[])
{
System.out.print("What char would you like? ");
EasyReader sym = new EasyReader();
String chars = sym.readWord();
System.out.print("How long would you like it to be? ");
int nums = sym.readInt();
System.out.print("Diag, Vert, or Hori? ");
//you want to read the __ varible, not the sym.readX()
String line = sym.readWord();
System.out.println("");
System.out.println("");
if(line.equals("Hori")){
for(int x = 0; x < nums; x++){
System.out.print(chars + " ");
}
}
else if(line.equals("Vert")){
for(int y = 0; y < nums; y++){
System.out.println(chars + " ");
}
}
else{
for(int xy = 0; xy < nums; xy++){
for(int spaces = 0; spaces < nums; spaces++){
spaces = spaces + 2;
System.out.print(spaces + " ");
System.out.println(chars);
}
}
}
}
}在底部,您将看到一个名为xy的for循环,它将读取行的长度。在这个for循环下,将控制空格。但是,由于某些原因,总和没有正确更新。输出始终为:
2 (char)
5 (char)
8 (char)
2 (char)
5 (char)
8 (char)
...输出应为:
2 (char)
4 (char)
8 (char)
...编辑*因为我现在需要帮助,所以这里是一个例子(所以我不需要在评论中解释太多)
例如:如果用户输入,他想要5个单位的行。有两个for循环,一个控制他想要的空格数量,另一个控制打印字符的数量,输出将是2,4,6,8,10。
发布于 2017-09-05 02:28:32
在for循环语句中,您可以说‘在每次迭代后将spaces增加1’(spaces++):
for(int spaces = 0; spaces < nums; spaces++){在您的循环主体中,您还要求将其增加2:
spaces = spaces + 2;所以每次迭代它都会增加3。
顺便说一句,你的嵌套循环似乎有问题(如果我没理解错的话)。如果外部循环(在xy上循环)在每次迭代中绘制一条线,那么应该为当前行输出缩进的内部循环必须以xy (乘以2)而不是nums为边界。我会这样写:
for (int xy = 0; xy < nums; xy++) {
for (int spaces = 0; spaces < xy*2; spaces += 2) {
System.out.print(" ");
}
System.out.println(chars);
}发布于 2017-09-05 02:27:59
因为您每次都会在空格中添加3
for(int spaces = 0; spaces < nums; spaces++){
spaces = spaces + 2;spaces++ spaces += 1
spaces =空格+ 2; spaces += 2
发布于 2017-09-05 02:57:07
实际上问题出在这一部分:
for(int spaces = 0; spaces < nums; spaces++){
spaces = spaces + 2;
System.out.print(spaces + " ");
System.out.println(chars);
}当程序启动时,我们有了spaces = 0
然后,此部分将运行spaces =spaces + 2
现在spaces等于2,所以我们有spaces = 2
在spaces使用spaces++部件按1递增之后,程序将打印2
现在spaces等于3,这意味着spaces=3
之后,这一行将运行spaces = spaces + 2
因此,spaces的值变成了5
如果我们永远这样做,我们就会得到这个数字序列:
2 5 8 11 14 ....
实际上,这是因为我们在每次迭代中通过3递增spaces
如果您在此表单中修改代码,问题将会得到解决:
for (int xy = 0; xy < nums; xy++) {
for(int spaces = 0; spaces < xy*2; spaces += 2)
System.out.print(spaces + " ");
System.out.println(chars);
}https://stackoverflow.com/questions/46042396
复制相似问题