输出未按预期打印

时间:2012-11-22 21:33:23

标签: java loops for-loop nested-loops

我的代码主要用于完成此任务,只是无法弄清楚导致输出不正确的原因。使用say,3和A作为值时所需的输出应该返回:

  
    

A

  
     

AA

AAA

目前,我收到了:

AAA

AAA

AAA

代码:

import static java.lang.System.*;

public class TriangleThree
{
private int size;
private String letter;

public TriangleThree()
{
}

public TriangleThree(int count, String let)
{
    size = count;
    letter = let;
}

public void setTriangle( String let, int sz )
{
    size = sz;
    letter = let;
}

public String getLetter()
{
    return letter;
}

public String toString()
{
    String output="";
    for(int i = 1; i<=size; i++)
    {
        for(int j = 0; j > i;j++ )
        {
            output = output + " ";
        }

        for(int k = size; k>0; k--)
        {
            output = output + letter;
        }
        output= output + "\n";
    }





    return output+"\n";
}
}

并与我的跑步者类交叉引用:

import static java.lang.System.*;

import java.util.Scanner;

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

                //instantiate a TriangleThree object
         TriangleThree tt = new TriangleThree( big, value );
            //call the toString method to print the triangle
            System.out.println( tt );

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

1 个答案:

答案 0 :(得分:2)

您正在运行第二次for循环3次(全部从size0)。将其更改为: -

    for(int k = i; k>0; k--)
    {
        output = output + letter;
    }

这将1 time i = 12 times i = 2,...

此外,您的第一个循环存在问题: -

for(int j = 0; j > i;j++ )

这应该是: -

for(int j = 0; j < i;j++ )

更新: -

实际上你不需要你的第一个循环,因为它只是打印空间。而是仅在第二个循环中为output添加空格: -

    for(int k = i; k>0; k--)
    {
        output = output + letter + " ";
    }