Three ways to get keyboard input values in Java
In the process of program development, the need to get input values from the keyboard is common, but Java it is not like the C language to provide us with scanf (), C + + gives us the CIN () to get the keyboard input value of the ready-made function! Java does not provide such a function does not mean that we do not have the experience of this situation, please see the following three ways to solve it:
Several methods are listed below:
Method One: Receive a character from the console and print it out
publicstatic void Main (String [] args) throws ioexception{
System.out.print ("Entera Char:");
Chari = (char) System.in.read ();
System.out.println ("Yourchar is:" +i);
}
}
Although this method implements the input character from the keyboard, System.out.read () can only be obtained for one character, and the type of the variable entered is only char, and when we enter a number, we want to get an integer variable, We also have to modify the variable types, which makes it more cumbersome.
Method Two: Receive a string from the console and print it out. In this topic, we need to use the BufferedReader class and the InputStreamReader class
publicstatic void Main (String [] args) throws ioexception{
BUFFEREDREADERBR = new BufferedReader (new InputStreamReader (system.in));
STRINGSTR = null;
System.out.println ("Enteryour value:");
Str= Br.readline ();
System.out.println ("Yourvalue is:" +str);
}
So we can get the string we entered.
Method Three: This method I think is the simplest, the most powerful, is to use the scanner class
publicstatic void Main (String [] args) {
SCANNERSC = new Scanner (system.in);
System.out.println ("Please enter your name:");
Stringname = Sc.nextline ();
System.out.println ("Please enter your Age:");
Intage = Sc.nextint ();
System.out.println ("Please enter your salary:");
Floatsalary = Sc.nextfloat ();
SYSTEM.OUT.PRINTLN ("Your information is as follows:");
System.out.println ("Name:" +name+ "\ n" + "Age:" +age+ "\ n" + "Salary:" +salary);
}
This code has shown that the scanner class, whether it's a string or integer data or a variable of type float, can do it with a little bit of change! No doubt he is the strongest!
Java Trivia Point (i) three ways to get keyboard input values---java