简体   繁体   中英

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);
    }
}

That exception occurs when you do not enter any char into the console (your String is empty). I recommend to write your code with a try/catch block.

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): ");

        try {
            gender = sc.nextLine();
            gender = gender.toUpperCase();
            genderChar = gender.charAt(0);
            System.out.println("Your gender is " + genderChar);
        } catch(Exception e) {
            System.out.println("No gender has been entered. Please, try again");
        }
    }
}

Possible outputs:

  • You not enter any char:

    Enter gender (Male/Female):
    No gender has been entered. Please, try again

  • You enter 'F' char:

    Enter gender (Male/Female): f
    Your gender is F

  • You enter any char:

    Enter gender (Male/Female): x
    Your gender is X

Maybe you would want to create a pattern or something like that to allow only 'F' and 'M' to be the correct characters.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM