- Inputs from the keyboard in Java
- How to use Keyadapter in Java?
- How use KeyEvent in Java?
- Get a Keyboard Input in Java
- Getting Keyboard Input Using BufferedReader in Java
- Getting Keyboard Input Using Scanner Class in Java
- Getting Keyboard Input Using Console Class in Java
- Getting Keyboard Input Using command-line arguments in Java
- Getting Keyboard Input
Inputs from the keyboard in Java
In our game we want to allow the user to operate the game using the keyboard.
- A common way to accomplish this is to use Java’s built-in KeyAdapter class. It is a class used to receive input from the keyboard.
- Further, we will also use the built-in KeyEvent class. When a key is pressed, released, or typed, the relevant method activates in the listener object, and KeyEvent transferres then to it.
- Finally, we then create a new class of our own, KeyInput, which will handle all button presses in the game.
How to use Keyadapter in Java?
Start by importing the classes:
import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent;
Then we inherit the KeyAdapter class which allows you to take inputs from the keyboard (Remember inheritance?)
public class KeyInput extends KeyAdapter < Game game;
Additionally, we create the constructor that takes the game object as instance variable
Further, what will happen when a key is pressed? We attache pressing the button to the object called game
public void keyPressed(KeyEvent e)
Finally, what happens when a key is released? We attach that command to the object called game
public void keyReleased(KeyEvent e) < game.keyReleased(e); >>
The complete set of code is:
import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; public class KeyInput extends KeyAdapter < Game game; public KeyInput(Game game)< this.game = game; >public void keyPressed(KeyEvent e) < game.keyPressed(e); >public void keyReleased(KeyEvent e) < game.keyReleased(e); >>[/vc_column_text][vc_empty_space height=”10px”][vc_separator type=”normal”][vc_empty_space height=”15px”][vc_column_text]
How use KeyEvent in Java?
We created our KeyInput class above that contains two methods, one for when we press a key and one for when we release a key. But now we want to make sure that the program actually detects which key is pressed.
Further, we will use the built-in methods VK_LEFT and VK_RIGHT found in KeyEvent to detect if it is the Left and Right arrow keys used.[/vc_column_text][vc_empty_space height=”40px”][vc_single_image image=”20081″ img_size=”large” alignment=”center” onclick=”link_image” qode_css_animation=””][vc_empty_space height=”40px”][vc_column_text]Let’s start by declaring a method for detecting if a key is pressed
public void keyPressed(KeyEvent e) < // New key press int key = e.getKeyCode(); // If we press right if (key == KeyEvent.VK_RIGHT) < System.out.println("The right arrow key is pressed"); // Or, if we press left >else if (key == KeyEvent.VK_LEFT) < System.out.println("The left arrow key is pressed"); >>
Additionally, what will happen when a key is released
public void keyReleased(KeyEvent e) < // New key has been released int key = e.getKeyCode(); // If we release the right key if(key == KeyEvent.VK_RIGHT)< System.out.println("The right arrow key is released"); >// If we release the left key else if(key == KeyEvent.VK_LEFT) < System.out.println("The left arrow key is released"); >>
Note, we can of course do the same for other keys. The Oracle KeyEvent page lists commands for the other keys
Finally, the complete set of code is:
public void keyPressed(KeyEvent e) < // New key press int key = e.getKeyCode(); // If we press right if (key == KeyEvent.VK_RIGHT) < System.out.println("The right arrow key is pressed"); // Or, if we press left >else if (key == KeyEvent.VK_LEFT) < System.out.println("The left arrow key is pressed"); >> public void keyReleased(KeyEvent e) < // New key has been released int key = e.getKeyCode(); // If we release the right key if(key == KeyEvent.VK_RIGHT)< System.out.println("The right arrow key is released"); >// If we release the left key else if(key == KeyEvent.VK_LEFT) < System.out.println("The left arrow key is released"); >>[/vc_column_text][vc_empty_space height=”20px”][vc_separator type=”normal”][vc_empty_space height=”40px”][/vc_column][/vc_row][vc_row css_animation=”” row_type=”row” use_row_as_full_screen_section=”no” type=”full_width” angled_section=”no” text_align=”left” background_image_as_pattern=”without_pattern”][vc_column][vc_column_text]
Get a Keyboard Input in Java
- Getting Keyboard Input Using BufferedReader in Java
- Getting Keyboard Input Using Scanner Class in Java
- Getting Keyboard Input Using Console Class in Java
- Getting Keyboard Input Using command-line arguments in Java
This tutorial introduces how to get a keyboard input or user input in Java. We also included example programs to help you understand this topic better.
To get a user input in Java, you’ll encounter several classes such as the Scanner , BufferedReader , and Console . We’ll use these classes for our operation as we show you the different methods you can follow.
Getting Keyboard Input Using BufferedReader in Java
In this example, we used the BufferedReader class that takes the InputStreamReader class’s instance to read a user input. Here, the readLine() method reads the user input and returns a string as a result:
import java.io.BufferedReader; import java.io.InputStreamReader; public class SimpleTesting public static void main(String[] args) BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter Input : "); try String s = br.readLine(); System.out.println(s); >catch(Exception e) System.out.println(e); > > >
Getting Keyboard Input Using Scanner Class in Java
The Scanner class is one of the simplest ways to get user input in Java. This class provides several built-in methods to get the input of various types like int and float. Here, we used the nextInt() method to get the int type of the input:
import java.util.Scanner; public class SimpleTesting public static void main(String[] args) System.out.println("Enter Input : "); Scanner scanner = new Scanner(System.in); int a = scanner.nextInt(); System.out.println(a); scanner.close(); > >
Getting Keyboard Input Using Console Class in Java
We can use the Console class to get user input in Java. This class belongs to the java.io package and provides the readLine() method to read user input from the console. See the example below:
import java.io.Console; public class Main public static void main(String[] args) Console console = System.console(); String str = console.readLine("Enter Input : "); System.out.println(str); > >
Getting Keyboard Input Using command-line arguments in Java
In Java, command-line arguments are the arguments that are passed during program execution. The main() method of the program has a string-type parameter that holds the input supplied from the terminal. Remember to get the command-line argument to pass them during program execution and that the type of input is always a string type.
public class SimpleTesting public static void main(String[] args) if(args.length>0) System.out.println("User Input"); for (int i = 0; i args.length; i++) System.out.println(args[i]); > >else System.out.println("No Input Found"); > >
Run the code and pass the keyboard input as command-line arguments.
java SimpleTesting Hello DelftStack
User Input Hello DelftStack
Accepting keyboard input in Java is done using a Scanner object.
Consider the following statement
Scanner console = new Scanner(System.in)
This statement declares a reference variable named console. The Scanner object is associated with standard input device (System.in).
To get input from keyboard, you can call methods of Scanner class. For example in following statment nextInt() method of Scanner takes an integer and returns to variable x :
import java.util.Scanner; // Needed for Scanner class /** * This program demonstrates keyboard input. */ public class RectangleArea < public static void main(String[] args) < int length; // To hold rectangle's length. int width; // To hold rectangle's width. int area; // To hold rectangle's area // Create a Scanner object to read input. Scanner console = new Scanner(System.in); // Get length from the user. System.out.print("Enter length "); length = console.nextInt(); // Get width from the user. System.out.print("Enter width "); width = console.nextInt(); // Calculate area. area = length * width; // Display area. System.out.println("The area of rectangle is " + area); >>
Some other useful methods of Scanner class
Returns the next token as an int.
Returns the next token as a float.
Returns the next token as a long.
Finds and returns the next complete token as a string ended by a blank.
Returns the rest of the current line, excluding any line separator at the end.
import java.util.Scanner; /** * This program demonstrates various Scanner methods. */ public class ReadEmployee < public static void main(String[] args) < String name; // To hold the employee's name int age; // To hold the employee's age char gender; // To hold the employee's gender double salary; // To hold the employee's salary // Create a Scanner object to read input. Scanner console = new Scanner(System.in); // Get the employee's name System.out.print("Enter name: "); name = console.nextLine(); // Get the employee's age System.out.print("Enter age: "); age = console.nextInt(); // Get the employee's gender System.out.print("Enter gender: "); gender = console.next().charAt(0); // Get the employee's salary System.out.print("Enter salary: "); salary = console.nextDouble(); // Display the information System.out.println("Name: " + name + " Age: " + age + " Gender: " + gender + " Salary: " + salary); >>
Enter name: Alex Joseph
Enter age: 24
Enter gender: M
Enter salary: 8000
Name: Alex Joseph Age: 24 Gender: M Salary: 8000.0
- Menu
- Java Fundamentals
- 1.1 Getting Started
- 1.2 Creating Your First Application
- 1.3 Parts of a Java Program
- 1.4 Variables and Literals
- 1.5 Primitive Data Types
- 1.6 Arithmetic Operators
- 1.7 Operator Precedence
- 1.8 Type Conversion and Casting
- Questions and Exercises
- 2.1 Class String
- 2.2 Objects and Reference Variables
- 2.3 Class Math Methods
- 2.4 String Methods
- 2.5 Reading Keyboard Input
- 2.6 Dialog Boxes for Input/Output
- 3.1 The if-else Statement
- 3.2 The if-else-if Statement
- 3.3 Nested if Statement
- 3.4 Logical Operators
- 3.5 Comparing String Objects
- 3.6 The switch Statement
- 3.7 Conditional Operator
- Questions and Exercises
- 4.1 The Increment and Decrement Operators
- 4.2 The while Loop
- 4.3 The do-while Loop
- 4.4 The for Loop
- 4.5 Nested Loops
- 4.6 The break and continue Statements
- Questions and Exercises
- 5.1 Introduction to Methods
- 5.2 void Methods
- 5.3 Passing Arguments to a Method
- 5.4 Local Variables
- 5.5 Returning a Value from a Method
- Questions and Exercises
- 6.1 Objects and Classes
- 6.2 Designing a Class
- 6.3 Constructors
- 6.4 Overloading Methods
- 6.5 UML Diagram
- Questions and Exercises
- 7.1 Introduction to Arrays
- 7.2 Processing Array Elements
- 7.3 Passing Arrays as Arguments to Methods
- 7.4 Common Array Operations
- 7.5 Returning Arrays from Methods
- 7.6 String Arrays
- 7.7 Arrays of Objects
- 7.8 Two-Dimensional Arrays
- 7.9 Variable-Length Argument Lists
- 7.10 The ArrayList Class
- Questions and Exercises
- 8.1 Static Class Members
- 8.2 Passing Objects as Arguments to Methods
- 8.3 Returning Objects from Methods
- 8.4 The toString Method
- 8.5 The this Reference Variable
- 8.6 Aggregation
- 8.7 Garbage Collection
- Questions and Exercises
- 9.1 What Is Inheritance?
- 9.2 Calling the Superclass Constructor
- 9.3 Overriding Superclass Methods
- 9.4 Protected Member
- 9.5 Multilevel Inheritance
- 9.6 The object Class
- 9.7 Polymorphism
- 9.8 Abstract Classes and Abstract Method
- 9.9 Interfaces
- 10.1 Introduction to File Input and Output
- 10.2 Writing Data to Text File
- 10.3 Reading Data from Text File
- 10.4 Reading and Writing Premitive Data
- 11.1 Handling Exception
- 11.2 Try Catch Block and Multi Catch
- 11.3 Finally Block
- 11.4 Try with Resources
- 11.5 Checked and Unchecked Exceptions
- 11.6 Rethrowing and Throwing an Exception
- 11.7 Creating Your Own Exception Classes
Getting Keyboard Input
To get keyboard input in Java, you can use the Scanner class from the java.util package. The Scanner class provides methods for reading input from the keyboard and parsing it into different data types (such as int , double , etc.).
Here is an example of how you can use the Scanner class to get keyboard input in Java:
Scanner input = new Scanner(System.in); System.out.print("Enter a number: "); int num = input.nextInt(); System.out.println("You entered: " + num);
In this example, the Scanner class is used to read an integer from the keyboard. The nextInt() method reads the next token of input as an int and returns it.
You can also use the nextLine() method to read a whole line of input as a string.
Scanner input = new Scanner(System.in); System.out.print("Enter a line of text: "); String line = input.nextLine(); System.out.println("You entered: " + line);
This code reads a whole line of text from the keyboard and stores it in the line variable.
Keep in mind that the Scanner class reads input in a blocking manner, which means that the program will wait for the user to enter input before continuing.
I hope this helps! Let me know if you have any other questions.