如何在java中输入字符

Sha*_*hid 0 java input char

在C中,我们可以使用char键盘中的关键字作为字符输入

scanf("%c", &ch);

但是在Java中如何做到这一点?

我试过这个:

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter a character: ");
    char c = scanner.next().charAt(0);
    System.out.println("You have entered: "+c);
  }
}
Run Code Online (Sandbox Code Playgroud)

unf*_*ous 5

您可以使用扫描仪从输入中读取:

Scanner scanner = new Scanner(System.in); 
char c = scanner.next().charAt(0); //charAt() method returns the character at the specified index in a string. The index of the first character is 0, the second character is 1, and so on.
Run Code Online (Sandbox Code Playgroud)