简体   繁体   English

为什么我不能用我的输出打印char类型值

[英]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.

相关问题 为什么我们不能将char类型变量的默认值设置为&#39;&#39; - why can't we set default value of char type variable to ' ' 如果 Oracle 数据库表中的列类型为 CHAR(4 BYTE),为什么我不能使用 JPA 更新长度为 3 的字符串的值的行? - Why I can't I use JPA to update a row with a value for a string with a length of 3, if the column type in an Oracle database table is CHAR(4 BYTE)? 为什么我不能打印2D阵列? - Why can't I print my 2D array? 为什么Char不打印,并且计数器超出了我的循环; - Why Char won't print, and counter exceeded my loop; 为什么我不能打印最大 long 值? - Why can't I print the maximum long value? 为什么在Java中的char值之后不能读取int值? - Why can't I read a int value after char value in Java? 为什么我不能将 int 类型值添加到数组中 - why I can't add int type value to an array 为什么我的 ArrayList 没有打印出 Java 中所需的输出? - Why doesn't my ArrayList print out the output desired in Java? 为什么我的 shell 脚本的输出没有在控制台中打印出来? - Why does the output of my shell script doesn't print in console? 为什么我不能将此价值传递给我的行动? - Why can't i pass this value into my action?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM