Home  >  Article  >  Java  >  What are the methods to enter a character in java

What are the methods to enter a character in java

王林
王林Original
2019-11-23 11:48:525978browse

What are the methods to enter a character in java

Several methods will be listed below:

Method 1: Receive a character from the console and print it out

public static void main(String [] args) throws IOException{
  System.out.print(“Enter a Char:”);
  char i = (char) System.in.read();
  System.out.println(“your char is :”+i);
  }
}

Although this method achieves obtaining input characters from the keyboard, System.out.read() can only obtain one character. At the same time, the type of the incoming variable can only be char. , when we input a number and hope to get an integer variable, we have to modify the variable type, which is more troublesome.

Method 2: Receive a string from the console and print it out. In this question, we need to use the BufferedReader class and the InputStreamReader class

public static void main(String [] args) throws IOException{
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  String str = null;
  System.out.println(“Enter your value:”);
  str = br.readLine();
  System.out.println(“your value is :”+str);
}  

so that we can get the string we input.

Method three: I think this method is the simplest and most powerful, which is to use the Scanner class

public static void main(String [] args) {
  Scanner sc = new Scanner(System.in);
  System.out.println(“请输入你的姓名:”);
  String name = sc.nextLine();
  System.out.println(“请输入你的年龄:”);
  int age = sc.nextInt();
  System.out.println(“请输入你的工资:”);
  float salary = sc.nextFloat();
  System.out.println(“你的信息如下:”);
  System.out.println(“姓名:”+name+“\n”+“年龄:”+age+“\n”+“工资:”+salary);
}

This code has shown that Scanner Whether the class is for strings, integer data or float type variables, you only need to make a small change to achieve the function! Undoubtedly it is the most powerful!

Recommended tutorial: java introductory tutorial

The above is the detailed content of What are the methods 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