Reputation: 434
I need to create a tree program using Java. I am unable to do this and ran out of ideas. It should use a for-loop and substring. Here is an example for a "sample" string:
S
SAS
SAMAS
SAMPMAS
SAMPLPMAS
SAMPLELPMAS
S
A
M
P
L
E
Here is what i have got so far:
Scanner input = new Scanner(System.in);
String userWord, reverse = "";
int size;
System.out.print("Enter a word that is less than or equal to 10 characters: ");
userWord = input.next();
userWord = userWord.toUpperCase();
size = userWord.length()-1;
for (int i = 1; i <= userWord.length() + 1; i++) {
System.out.print(userWord.substring(0, i));
System.out.println(userWord.substring(0,i-1));
}
Thanks for any help.
Upvotes: 0
Views: 384
Reputation: 13934
public static void main (String[] args) throws java.lang.Exception
{
Scanner input = new Scanner(System.in);
String userWord, reverse = "";
int size;
StringBuilder padding = new StringBuilder();
System.out.print("Enter a word that is less than or equal to 10 characters: ");
userWord = input.next();
userWord = userWord.toUpperCase();
reverse = new StringBuffer(userWord).reverse().toString();
size = userWord.length();
for(int i = 0; i < size; i++){
padding.append(" ");
}
for (int i = 1; i <= size; i++) {
System.out.print(padding.substring(0, size-i));
System.out.print(userWord.substring(0, i));
if(i > 1){
System.out.println(reverse.substring(size+1-i, size)); //2 >= i
}else{
System.out.println("");
}
}
String pad = padding.substring(0, size-1).toString();
for(int i = 0; i < size; i++){
System.out.println(pad + userWord.charAt(i));
}
}
Upvotes: 1
Reputation: 513
You are currently using one for loop. You would need two. the first would go through the col and then row
for (int x = 1; x <= input; x++)
{
for (int y = 0; y < x; y++)
{
System.out.print( // enter what you need here);
}
System.out.println();
}
Does that make any sense? Let me know if you still have problems
Upvotes: 0