📜  Java中的 Scanner 和 nextChar()

📅  最后修改于: 2022-05-13 01:55:31.342000             🧑  作者: Mango

Java中的 Scanner 和 nextChar()

Java中的 Scanner 类支持 nextInt()、nextLong()、nextDouble() 等。但是没有 nextChar()(请参阅此示例)

要读取一个字符,我们使用next().charAt(0) 。 next()函数将输入中的下一个标记/单词作为字符串返回,而 charAt(0)函数返回该字符串中的第一个字符。

// Java program to read character using Scanner 
// class
import java.util.Scanner;
public class ScannerDemo1
{
    public static void main(String[] args)
    {
        // Declare the object and initialize with
        // predefined standard input object
        Scanner sc = new Scanner(System.in);
   
        // Character input
        char c = sc.next().charAt(0);
   
        // Print the read value
        System.out.println("c = "+c);
    }
}

输入 :

g

输出 :

c = g