This then gives me the error of "String index out of range: 0". What's the problem with the code? Why is it saying that s is empty when I've set it to "1"?
Don Nguyen wrote:I can summarize my problem into this:
This then gives me the error of "String index out of range: 0". What's the problem with the code? Why is it saying that s is empty when I've set it to "1"?
These 2 lines do not cause you an error. Show us all code you got, mistake somewhere else in your code.
You guys are right. From now on, I won't try to "summarize" my code. Here's the code:
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:646)
at LookAndSaySequence.main(LookAndSaySequence.java:11)
Also, if you guys happen to feel like it, suggest anything with syntax, add tips to make my code more efficient or readable, and anything else that may come to mind. I'm more of a noobie.
Another thing, what my code is trying to do is print a term in the "Look-and-say Sequence" on each line, starting from the first term in the sequence, with the number of lines specified in the variable 'rows'.
Well, obviously, it is not the first iteration that fails. You have an iteration where your inner loop doesn't do anything. This leaves curNum remaining as "", which of course, makes prevNum as "". And it is the following iteration that fails.
Interesting problem. Actually, the problem is on Line 14. On the very first time through, your variable prevNum is "1". Since your loop index j is initialized to 1, you immediately go past the end of prevNum when you try to access charAt(1) on Line 15. I don't think you have implemented the algorithm correctly.
If I were to implement this algorithm, I would try to make the code describe it as English-like as possible. And I'd pick less confusing names. The name prevNum is kind of confusing because it's actually the number I'm currently looking at. That kind of thing messes with your brain and screws up your thinking. It's the Stroop Effect
Yeah, it helps if you break it down into smaller chunks. I broke it down into lookAndSay a number, count repeats of a character, and a main loop to lookAndSay a series of numbers.
Here's the results up to the twelfth # in the series:
Post by:autobot
My previous laptop never exploded like that. Read this tiny ad while I sweep up the shards.
a bit of art, as a gift, the permaculture playing cards