Reputation: 55
How would I do this?
Give me a word > sugar
s
su
sug
suga
sugar
Here is what I have so far:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a word:");
String word = scan.nextLine();
int length = word.length();
for(int number = 0; number < length; number++){
System.out.println(word.charAt(number));
}
}
This makes the word display letter by letter.
Upvotes: 0
Views: 108
Reputation: 8338
I would suggest using String.substring(int startIndex, int endIndex)
.
For you, your program would look like this:
String s = "Sugar";
for(int i = 0; i < s.length() - 1; i++) {
System.out.println(s.substring(0,i));
}
Keep in mind that startIndex is inclusive, endIndex is exclusive. So "Sugar".substring(0,3)
will give "Sug".
Upvotes: 4
Reputation: 347314
One approach would be to use a form of String
concaternation...
String word = "Sugar";
int length = word.length();
StringBuilder sb = new StringBuilder(word.length());
for (int number = 0; number < length; number++) {
sb.append(word.charAt(number));
System.out.println(sb.toString());
}
Basically, this appends each character to the builder on each loop, printing the results...
S
Su
Sug
Suga
Sugar
Another approach might be to use a compound loop...
String word = "Sugar";
int length = word.length();
for (int number = 0; number < length; number++) {
for (int inner = 0; inner < number; inner++) {
System.out.print(word.charAt(inner));
}
System.out.println("");
}
The outer (first) loop controls the number of characters you want to print, the inner (second) loop physically prints each character from the start to the number of characters you want to print...(nb: This will print a leading empty space, so you might need a if
in there to control that if it's important)
Upvotes: 3