用于打印字母的java For循环
public class LetterPrint {
int totalLines;
int consecLines;
int timesPrintedinLine;
int linesPrinted;
char currentChar;
LetterPrint(int totalLines, int consecLines){
this.totalLines = totalLines;
this.consecLines = consecLines;
}
void beginPrinting(){
for(timesPrintedinLine = 0; linesPrinted<=totalLines; timesPrintedinLine++)
{
Print();
}
}
public char correctChar(){
if(timesPrintedinLine/(consecLines*4) == 1)
return currentChar = 'A';
else
return currentChar = 'B';
}
void Print(){
if (timesPrintedinLine%5 !=0)
System.out.print(correctChar());
else{
System.out.println();
linesPrinted = timesPrintedinLine/4;
}
}
}
有人能帮我看看为什么用“LetterPrint letterPrinter=new LetterPrint(6,1);”创建时这个物体正在打印
BBBA
AABB
BBBB
BBBB
BBBB
BBBB
而不是
AAAA
BBBB
AAAA
BBBB
AAAA
BBBB
我感谢任何能帮我澄清此事的人
# 1 楼答案
既然原始代码不是“最好的”,我就重写了它:
# 2 楼答案
尽可能地更正了代码
产量与预期一致
所做的改变是
for
循环从1
开始,以避免打印第一个空行李>correctChar
中的条件已更改,以适应后续的更改。(您的仅限于第一次迭代)如果你想要解释,请询问
# 3 楼答案
逐步完成每个过程
timesPrintedInLine
是第一个0,所以在Print()
中它将打印一行新行。当timesPrintedInLine
为1时,1不是5的倍数,因此System.out.print
将在Print()
中打印从correctChar()
返回的char
;因为1/(1*4)不等于1,所以打印B
。同样的情况也发生在2和3上当
timesPrintedInLine
为4时,我们再次转到correctChar()
A
这次打印timesPrintedInLine
现在变为5,所以打印一个新行,linesPrinted
现在等于5/4,或1对于
timesPrintedInLine
=6和7,打印A
,因为6/4和7/4等于1从这一点开始,
timesPrintedInLine
将始终大于7。随后,timesPrintedInLine
/(1*4)永远不能等于1,这就是为什么总是打印B
(除非timesPrintedInLine
是5的倍数;在这种情况下,打印一个新行,并且linesPrinted
等于timesPrintedInLine
/4)问题来自
if
语句,因此将其更改为:# 4 楼答案
首先,TimesPrintedLine和LineSprint的约定和最佳实践需要声明为局部变量。 第二,不要经常给系统打电话。出去
现在正确的代码可以是:
}