[英]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 请输入你的名字:shuvo
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 48 线程“main”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围: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'
的索引对应的字符。
'0'
is of char
type, which is actually numeric, and its decimal value is 48
. '0'
是char
类型,实际上是数字,其十进制值是48
。 As you input doesn't have 48 characters, you get the ArrayIndexOfOfBoundsException
. 当您输入没有48个字符时,您将获得
ArrayIndexOfOfBoundsException
。
Use: 采用:
user.next().charAt(0);
which will return you the first character from the input. 这将返回输入中的第一个字符。
或者干脆
char name=user.next().charAt(0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.