Java中的Scanner类对于输入有着多种方法;其中:

  • String 有对应的 nextLint ( ) 或 next ( ) ;
  • Int 有对应的 nextInt ( ) ;
  • Float 有对应的 nextFloat ( ) ;
  • Double 有对应的 nextDouble ( ) ;
  • 但 char 类型却 没有对应的 nextChar ( ) ;

更多Scanner的使用可移步:Scanner对象

那char类型该如何用 Scanner对象来输入呢?

       有两种办法:

方法一:System.in.read() 可以实现输入一个字符,返回字符的ASCII码,然后强制类型转换转回字符

public class Demo {
   public static void main(String[] args) throws Exception{
       char c;
       c = (char)System.in.read();
       System.out.println(c);
   }
}

System.in.read ( ) :从键盘读取一个字符,返回字符的Unicode码;
 

详细说明:System.in中的read ( ) 方法

方法二:通过录入字符串的第一个字符来实现

import java.util.Scanner;
public class Demo {
    public static void main(String[] args) throws Exception{
        char c;
        Scanner sc = new Scanner(System.in);
        c = sc.next().charAt(0);
        System.out.println(c);
    }
}

java.lang.String.charAt() 方法返回指定索引处的char值;
索引范围从0到 length()-1 ;序列的第一个char值的索引为0;
 
以下是 java.lang.String.charAt() 方法的声明

public char charAt(int index)
  • 参数 index 是序列的索引位置 (0 到 length()-1)
  • 此方法返回这个字符串的指定索引处的char值;
  • 异常:IndexOutOfBoundsException – 如果index的参数为负或不小于该字符串的长度
Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐