简体   繁体   中英

why i can't print char type value with my output

package practice;

import java.util.Scanner;

public class Shuvo {

    public static void main(String[] args) {
        System.out.print("please Enter your name: ");
        char name;
        Scanner user= new Scanner(System.in);
         name = user.next().charAt('0');
        System.out.println("HELLOW" +name); //<- why this isn't working??
        user.close();
    }
}

output:

please Enter your name: shuvo

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

at java.lang.String.charAt(Unknown Source)
at practice.Shuvo.main(Shuvo.java:11)

user.next().charAt('0'); will return the character that corresponds to the index with number '0' .

'0' is of char type, which is actually numeric, and its decimal value is 48 . As you input doesn't have 48 characters, you get the ArrayIndexOfOfBoundsException .

Use:

user.next().charAt(0);

which will return you the first character from the input.

或者干脆

char name=user.next().charAt(0);

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