1

I'm trying to print the last name character, but my code is generating an exception.

Code:

import java.util.Scanner;

public class LastCharacter {


    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        System.out.println("Type your name: ");
        String name = reader.nextLine();
        char nameLastChar = lastCharacter(name);
        System.out.println("Last character = " + nameLastChar);


    }


    public static char lastCharacter(String text){

        int last = text.length();
        char lastChar = text.charAt(last);
        return lastChar;
    }


}

Exception:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 7

I can't find my mistake and I don't understand the exception information.

0

1 Answer 1

5

If a String is 7 characters long, the last index is 6, not 7. Remember, indexing starts at 0.

You want

int last = text.length() - 1; // Adjust the index
char lastChar = text.charAt(last);
Sign up to request clarification or add additional context in comments.

2 Comments

Maaaan thanks a lot :) Now I understand exception message. Have a godd day and thanks once again :)
@Kempa please be corteus and mark this answer as correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.