cosmo cosmo - 3 months ago 21
Java Question

charAt(0) String index out of range: 0

I'm trying to get user input on their gender, and convert it to a char and uppercase.

However, I keep getting this error: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.lang.String.charAt(Unknown Source) at InfoDisplay.main(InfoDisplay.java:12)

import java.util.Scanner;
public class InfoDisplay {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);

String gender;
char genderChar;

System.out.print("Enter gender (Male/Female): ");
gender = sc.nextLine();
gender = gender.toUpperCase();
genderChar = gender.charAt(0);


System.out.println("Your gender is " + genderChar);
}
}

Answer

Try this..

import java.util.Scanner;
    public class InfoDisplay {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);

        String gender;
        char genderChar;

        System.out.print("Enter gender (Male/Female): ");
        gender = sc.next(); //It will not take Enter as an input
        gender = gender.toUpperCase();
        genderChar = gender.charAt(0);


        System.out.println("Your gender is " + genderChar);
    }
}

If you are using sc.nextLine() to take String as an input, It will consider Enter as input of String when you are pressing it after entering input so you can use another alternate of sc.nextLine(). You can use sc.next() If your input string doesn't contain space so it will work here.

Comments