Bluasul Bluasul - 1 month ago 5
Java Question

In Java, how does one develop a loop that prints out a string like this (details in description)?

If I have a string like "lollipop", how can I make a loop that prints it out as:

l
lo
lol
loll
lolli
lollip
lollipo
lollipop


Would using arrays be necessary? Is there a way to do it without using arrays?

I tried this:

int x = 0;
String word = "lollipop";
while (x < word.length())
{
System.out.println(word[x]);
x += 1;
}


But obviously discovered that doesn't work, and if it did I still wouldn't get the output I want. I'd like to find a way to do it without arrays.

Answer

how can I make a loop that prints it out ...

That is the point of your exercise. You need to work that out for yourself.

Would using arrays be necessary? Is there a way to do it without using arrays?

No, and Yes.

System.out.println(word[x]);

That is the wrong approach. You cannot treat a String as an array.

Big Hint: look at the substring method(s) in String javadocs. Here's the link to the javadoc: http://docs.oracle.com/javase/8/docs/api/java/lang/String.html

Comments