0

我遇到了一个问题,它没有按应有的方式打印出来,并且无法弄清楚它是什么。

现在我的代码正在打印出这个:

***#

***##

***###

当它应该像这样打印出来时:

***#

**##

*###

这是我现在的代码:

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;
}
}

和我的交叉引用跑步者类:

import static java.lang.System.*;

import java.util.Scanner;

public class Lab11e
{
 public static void main( String args[] )
 {
   Scanner keyboard = new Scanner(System.in);
    String choice="";
        do{
            out.print("Enter the size of the box : ");
            int big = keyboard.nextInt();
            //out.print("Enter a letter : ");
            //String value = keyboard.next();

                //instantiate a TriangleFour object
         Box box = new Box( big);
            //call the toString method to print the triangle
            System.out.println( box );

            System.out.print("Do you want to enter more data? ");
            choice=keyboard.next();
        }while(choice.equals("Y")||choice.equals("y"));
}
}

我的想法是,我非常接近得到它,但就是不知道是什么。

4

1 回答 1

1
    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"; 
    }
于 2012-11-23T00:29:11.517 回答