Regardless of the solution, please start using a StringBuilder. Using += to append to your String is quite inefficient. Your code, modified to use StringBuilder:
As you see the core stays the same, there are just four changes:
- declare rev as StringBuilder instead of String.
- initialize it with a new StringBuilder. The constructor I used will create an empty StringBuilder that will initially have a capacity for nextLine.length() characters.
- use the append method instead of +=.
- return rev.toString() instead of rev itself.
Rob's example just demonstrates how to use a StringBuilder. He didn't incorporate Samrat's changes, which reads the String back to front and create a new String. If you are getting an empty String back sometimes from your rev() function, it means you are passing in an empty String. That is, maybe your scanner isn't working, or the way you are typing in input is a bit wonky. I'd put a println() at the top of the rev() method, so you can see what the input is.
oh, okay, i understand. i can fix that. i have one more question. the code i'm using for another method should allow the user to put in a number and get back a number in an array. iota (the method) at 0 would be 1001, at 1 would be 2002, at would be 3003, etc., and this array needs to help n numbers.
at the moment, if i enter IOTA followed by a number, i get back the number of 0s that corresponds to the value i entered. typing iota 4 gets me 0 0 0 0 because i have n initialized to 0.
therefore, i need to n needs to be the length of the input? i get an "exception in thread main" error when i try that. here's the code i'm using to test it:
Hmm, I don't get that. Your iota() method does some of the right things, but then returns null. In your calling code, the a.length should cause a NullPointerException. Are you sure you defined iota() that way?
What I don't understand is how they changed the earth's orbit to fit the metric calendar. Tiny ad:
Devious Experiments for a Truly Passive Greenhouse!