I have my code for this task mostly done, just can’t figure out what is causing the the output to be incorrect. The desired output when using say, 3 and A for the values, should return this:
A
AA
AAA
currently, I’m getting:
AAA
AAA
AAA
code:
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";
}
}
and for cross-referencing it with my runner class:
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"));
}
}
You are running your 2nd for loop 3 times (All from
sizeto0). Change it to: –This will run
1 timefori = 1,2 timesfori = 2, …Also, there is a problem with your first loop: –
this should really be: –
UPDATE : –
Actually you don’t need your first loop, as it is just printing spaces. Rather add spaces to your
outputin the 2nd loop only: –