gpt4 book ai didi

java - 使用 for 循环更新总和(例如 spaces = spaces + 2)

转载 作者:行者123 更新时间:2023-11-29 04:26:30 30 4
gpt4 key购买 nike

好的,我正在制作一个程序,它也可以制作垂直线、水平线和对角线!我对我的一个没有任何意义的输出感到困惑。

所以我的伪代码是这样的:

  //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。

最佳答案

for循环语句,你说'增加spaces每次迭代后加一”(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);
}

关于java - 使用 for 循环更新总和(例如 spaces = spaces + 2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46042396/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com