UMG90
UMG90

Reputation: 9

Can't get charAt(0) to work

Ok, so I can't seem to get this to work, though many people have told me the syntax and logic is correct. Can anyone reveal for me what I could possibly be doing wrong?

public Scanner in = new Scanner(System.in);

public void movePlayer() {
    System.out.print("move: ");
    String str = in.nextLine();

    in.nextLine();

    char c = str.charAt(0);

    if (c == 'l' || c == 'L') {
        player.moveLeft();
    }
 }

The program gets caught at char c = str.charAt(0);

And I am being returned this error:

java.lang.StringIndexOutOfBoundsException: String index out of range: 0 (in java.lang.String)

Upvotes: 0

Views: 7607

Answers (6)

Vivek Collur
Vivek Collur

Reputation: 1

Use in.next() instead. For whatever reason, nextLine() doesn't work with CharAt() sometimes.

Upvotes: 0

If you press Enter key in console, Scanner will be considered a complete line, regardless of whether or not there is text entered.

Press Enter at the beginning of a line, returns a String "" to the method Scanner.nextLine().

Add a check with str.lenght () > 0 before str.charAt(0).

Upvotes: 0

Greg Kopff
Greg Kopff

Reputation: 16585

You don't want to use nextLine(). You want to use next().

String str = in.next();

This is the Javadoc for nextLine()

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

You want next() instead:

Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.

This will stop you from consuming the empty line and raising an exception.

Upvotes: 3

CyprUS
CyprUS

Reputation: 4239

Add a check for Empty String and Null as well . You will avoid a lot of headaches.

Upvotes: 0

Kai
Kai

Reputation: 39641

This means that str is empty. You should check if it is not null and not empty.

if (str != null && !str.isEmpty()) {
...
}

Upvotes: 0

user1335794
user1335794

Reputation: 1092

you did not input anything though the console, so str is empty. this is the reason why chatAt(0) throw an exception

Upvotes: 5

Related Questions