0

我已经完成了这项任务的代码,只是无法弄清楚是什么导致输出不正确。当使用 3 和 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"));
}
}
4

1 回答 1

2

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

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

这将运行, 1 timefor , ...i = 12 timesi = 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 + " ";
    }
于 2012-11-22T21:36:10.740 回答