Reputation:
Implement the printTriangle method so that it prints a triangle out of the letters in parameter str. For example, if str is Chicken then your method should print the following
C
Ch
Chi
Chic
Chick
Chicke
Chicken
Also What if I wanted it to go from the full word chicken to c and also a different one that starts with the last letter and builds up to the whole word?
public class Triangle {
public void printTriangle(String str) {
for (int x = 1; x < str.length(); x++){
}
for ( int y = 0 ; y < ; y ++ ){
System.out.print(str.substring(y))
System.out.println( );
}
this is what I have :(
//should look like a triangle
Upvotes: 0
Views: 1938
Reputation: 1148
Something like this should work.
String str = "Chicken";
for(int y = 1; y <= str.length(); y++) {
System.out.println(str.substring(0, y));
}
C
Ch
Chi
Chic
Chick
Chicke
Chicken
And other combination:
String str = "Chicken";
for(int y = 0; y < str.length(); y++) {
System.out.println(str.substring(y));
}
Chicken
hicken
icken
cken
ken
en
n
String str = "Chicken";
for(int y = str.length() - 1; y >= 0 ; y--) {
System.out.println(str.substring(y));
}
n
en
ken
cken
icken
hicken
Chicken
Upvotes: 0
Reputation: 395
This Is what you are looking for. Ignoring syntax error in your code, the problem is you are doing substring of a string, so when you start with Chicken, and you are getting a substring of say... 0(the start) you are getting Chicken, at substring 1, you are getting hicken. You can do what you are trying to do using my following example.
public static void printTriangle(String str) {
String temp = "";
for (int x = 0; x < str.length(); x++){
temp += str.charAt(x);
System.out.println(temp);
}
}
Upvotes: 0
Reputation: 37
I tried some things for this but my best method was this:
public static void printOutWordAsTriangle(String word) { //Supply a String as the word to print
int currentLetter = 0; //The amount of letters which are printed per line. 0,1,2... (So it looks like a triangle)
char[] letters = word.toCharArray(); //Split the string into a char Array
while (currentLetter < letters.length) { //Print every line
String toPrint = "";
int i = 0;
for (char c : letters) { //Print all characters needed for the word-part of the line
if (i <= currentLetter) { // check if the character belongs to it
toPrint = toPrint + String.valueOf(c);
}
i++;
}
System.out.println(toPrint); // Print the line
currentLetter++;
}
}
Now, you can use this method. You just need to supply a String. Example:
printOutWordAsTriangle("WeLoveChicken");
Note: This will only print out the word in one direction. To the second, I am confident that you can do it.
Upvotes: 0
Reputation: 359
Try this one:
public class Triangle {
public void printTriangle(String input) {
for(int i = 0; i < input.length(); ++i) {
System.out.println(input.substring(0, i + 1));
}
}
public static void main(String[] args) {
new Triangle().printTriangle("Chicken");
}
}
Upvotes: 1