KaiquanMah's picture
Create 12b. Letter triangle
78bbc3c verified
raw
history blame
1.11 kB
Write a program that asks the user to enter a string.
The program will then print a triangle of letters corresponding to the string, as shown in the sample printouts below.
Example output:
Give a string: hello
h
he
hel
hell
hello
import java.util.Random;
import java.util.Scanner;
public class Test{
public static void main(String[] args){
final Random r = new Random();
//ADD
Scanner reader= new Scanner(System.in);
System.out.print("Give a string: ");
String user_str = String.valueOf(reader.nextLine());
int wordLastIdx = user_str.length() - 1;
for (int i = 0; i <= wordLastIdx; i++) {
System.out.println(user_str.substring(0, i+1));
}
}
}
Testing with input abcdef
Give a string: abcdef
a
ab
abc
abcd
abcde
abcdef
Testing with input hi
Give a string: hi
h
hi
Testing with input xxxxx
Give a string: xxxxx
x
xx
xxx
xxxx
xxxxx
Testing with input goodevening
Give a string: goodevening
g
go
goo
good
goode
goodev
goodeve
goodeven
goodeveni
goodevenin
goodevening