Home  >  Article  >  Java  >  How to enter a character in java

How to enter a character in java

王林
王林Original
2019-11-20 15:46:468528browse

How to enter a character in java

Idea:

First create a Scanner object, call the next() method of the Scanner object to obtain the string input by the console, and return It is a String type. Since there is no nextChar() method, the charAt(0) method of String is called to get the first character. In this way, we input a string.

Method to enter a character:

import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
char c = scanner.next().charAt(0);	

This is by far the most commonly used method, which is the black letter principle above.

import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
char c = scanner.next().toCharArray()[0];

This one is so-so to use, not as easy to use as the first one, a waste of resources, and not as simple as the first one.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
char c = (char)new BufferedReader(new InputStreamReader(System.in)).read();

Recommended tutorial: Getting started with java development

The above is the detailed content of How to enter a character in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn