charAt()
I'm new to programming and am trying to figure out why the following program will not produce the desired results. It's supposed to read a string, then print each character of the string on a new line.
I've tried do loops and for loops, changed the 'letter' variable to a char, and everything else I could think ofany ideas? Thanks.
import cs1.Keyboard;
publicclass OneChar{
publicstaticvoid main (String[] args){
String input;
char letter = 0;
System.out.print("Enter a string: ");
input = Keyboard.readString();
while (input.charAt(letter) <= input.length())
{
System.out.println(letter);
letter++;
}
System.out.println("Done");
}
}
[1323 byte] By [
mts767] at [2007-9-26 3:10:14]

If csl.Keyboard is a class used for reading input, it would be helpful to see that class in order to figure out the code. At the very least, you should print out what you read in using that class to verify that it contains what you think it contains.Rich
Second d'oh!
In your "while" statement, you don't want to compare the character at the current position to the length of the string, you want to compare an int that is set to the index of the current position. In other words, instead of:
while (input.charAt(letter) <= input.length())
you want:
while (letter <= input.length())
I think you can use a char, but I don't know why you'd use a char instead of an int.
Rich
Did you forget to remove the <= and put a < instead?
Remember, indexes are 0 bound, so if your string has 12 characters, they will be numbered 0 to 11. With <=, you would be checking character #12, which is not valid, hence the "index out of bounds" error.
(of course, Java is smart enough to tell you that your string is from 0 to 11 and 12 is too high. In C/C++, you would just have gotten garbage, because character #12 would be part of another variable.)
btw, you should use int letter instead of char letter. letter is an index into your string, therefore it's a number not a character itself.
Good luck
import cs1.Keyboard;
public class OneChar {
public static void main (String[] args) {
String input;
System.out.print("Enter a string: ");
input = Keyboard.readString();
for( int i=0; i<input.length(); i++ )
System.out.println( input.charAt( i ) );
>