Java 没有得到想要的结果,我很困
我遇到了一个问题,它没有像应该的那样打印出来,并且无法弄清楚它是什么 现在我的代码正在打印以下内容:Java 没有得到想要的结果,我很困,java,loops,nested-loops,Java,Loops,Nested Loops,我遇到了一个问题,它没有像应该的那样打印出来,并且无法弄清楚它是什么 现在我的代码正在打印以下内容: ***# ***## ***### 当它应该像这样打印出来时: ***# **## *### 以下是我目前的代码: import static java.lang.System.*; public class Box { private int size; public Box() { } public Box(int count) { size = count; }
***#
***##
***###
当它应该像这样打印出来时:
***#
**##
*###
以下是我目前的代码:
import static java.lang.System.*;
public class Box
{
private int size;
public Box()
{
}
public Box(int count)
{
size = count;
}
public void setSize(int count)
{
size = count;
}
public int getSize()
{
return size;
}
public String toString()
{
String output="";
for(int i = 1; i <= size; i++)
{
for(int k = size; k >0; k--)
{
output += "*";
}
for(int j = size; j >size-i; j--)
{
output += "#";
}
output += "\n";
}
return output;
}
}
我的想法是,我很快就能得到它,但就是不知道是什么。
(i i=1;我尝试使用描述性变量名。而不是i,j,k考虑行、COL等),我的实验表与这个实验室相关联的是什么,这就是原因。我不确定行、COL等在这个实验室中应用得很好,如果有一种方法,用2的方法在主环内嵌套,只需循环。已将此版本添加到解决方案中。要查看发生的情况有点困难,但会为每个项目保存一个条件。
for(int i = 1; i <= size; i++)
{
// Using a single for to make sure we don't create too many items.
// Also note the +1. It seems that when size = 3, you want 4 chars
// per line, so this take that extra char into account.
for(int k = 0; k < size + 1; k++)
{
// Use an if to decide if we print * or #.
// As 'i' gets bigger, we need to put less *, so
// we subtract 'i' from the total size. This tells
// when the midpoint has passed and we should start
// writing #s.
if (k <= size - i)
output += "*";
else
output += "#";
}
output += "\n";
}
for(int i = 1; i <= size; i++)
{
// Using a single for to make sure we don't create too many items.
// Also note the +1. It seems that when size = 3, you want 4 chars
// per line, so this take that extra char into account.
for(int k = 0; k < size + 1; k++)
{
// Use an if to decide if we print * or #.
// As 'i' gets bigger, we need to put less *, so
// we subtract 'i' from the total size. This tells
// when the midpoint has passed and we should start
// writing #s.
if (k <= size - i)
output += "*";
else
output += "#";
}
output += "\n";
}
for(int i = 1; i <= size; i++)
{
// Adds a number of * inversely proportional to the current
// value of 'i'.
for(int k = 0; k <= size - i; k++)
{
output += "*";
}
// Start adding # where we stopped the *.
for(int j = size - i; j < size; j++)
{
output += "#";
}
output += "\n";
}