没有得到理想的结果,我很困难

时间:2012-11-22 23:49:39

标签: java loops nested-loops

我遇到了一个问题,就是它没有像它应该的那样打印出来,也无法弄清楚它是什么。

现在我的代码正在打印出来:

  

***#

     

***##

     

***###

应该像这样打印出来:

  

***#

     

**##

     

*###

这是我现在的代码:

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

我的想法是,我非常接近它,但却无法弄清楚是什么。

1 个答案:

答案 0 :(得分: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"; 
    }