How to get the user input in Java?
You can use any of the following options based on the requirements.
Scanner
class
import java.util.Scanner;
//...
Scanner scan = new Scanner(System.in);
String s = scan.next();
int i = scan.nextInt();
BufferedReader
and InputStreamReader
classes
import java.io.BufferedReader;
import java.io.InputStreamReader;
//...
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int i = Integer.parseInt(s);
DataInputStream
class
import java.io.DataInputStream;
//...
DataInputStream dis = new DataInputStream(System.in);
int i = dis.readInt();
The readLine
method from the DataInputStream
class has been deprecated. To get String value, you should use the previous solution with BufferedReader
Console
class
import java.io.Console;
//...
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());
Apparently, this method does not work well in some IDEs.
Implementing User Input in Java code project - beginner
There is a very simple solution for this, and just as you guessed, it's using the Scanner library! So first you import the library by putting this snippet of code at the top of the class
import java.util.Scanner;
(You can also use * instead of Scanner so that you can use any library in java.util)
Then in order to use the Input class, you use the snippet of code below;
Scanner input = new Scanner(System.in);
Then, if you want to ask the user for his/her name, then first you prompt them by using the print commandl
System.out.println("What is your name?);
Lastly, you allow them to input a String value.
String name = input.nextLine();
For an integer it would be .nextInt(), for a double it would be .nextDouble(), for a float it would be .nextFloat() and so on and so on.
Please refer to the documentation in the link below for more help. Hope this solved your question! :D
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
java how to get user input
Scanner keyboard= new Scanner(System.in);
int answer= keyboard.nextInt();
In the above code a Scanner
object is created in the heap memory and its reference is stored in a variable called keyboard
(keyboard
varible is stored in stack memory). Using variable keyboard
you can able access the Scanner
object at any point of the program.
int answer= new Scanner(System.in).nextInt();
In the second statement you are creating object which is also stored in heap memory , but the reference of the object is not stored in any variable. So you cannot able to access this object anymore. After this statement the object in heap memory are ready to be garbage collected , since its reference is not used anymore.
Get User Input and show it on field - Java
Below code is a rewrite of your GUI application.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Login {
private JCheckBox c1;
private JPasswordField confirmPasswordText;
private JPasswordField passwordText;
private JRadioButton femaleButton;
private JRadioButton maleButton;
private JTextArea textArea;
private JTextField emailText;
private JTextField nameText;
private void createAndDisplayGui() {
JFrame frame = new JFrame("Registration");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createHeading(), BorderLayout.PAGE_START);
frame.add(createForm(), BorderLayout.CENTER);
frame.add(createButtonsPanel(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JButton createButton(String text,
int mnemonic,
ActionListener listener) {
JButton button = new JButton(text);
button.setMnemonic(mnemonic);
button.addActionListener(listener);
return button;
}
private JPanel createButtonsPanel() {
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(createButton("Submit", KeyEvent.VK_S, this::submit));
return buttonsPanel;
}
private JPanel createForm() {
JPanel form = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets.bottom = 5;
gbc.insets.left = 10;
gbc.insets.right = 10;
gbc.insets.top = 0;
JLabel nameLabel = new JLabel("Name");
form.add(nameLabel, gbc);
gbc.gridx = 1;
nameText = new JTextField(16);
form.add(nameText, gbc);
gbc.gridy = 1;
form.add(createRadioButtons(), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
JLabel eMailLabel = new JLabel("E-mail");
form.add(eMailLabel, gbc);
gbc.gridx = 1;
emailText = new JTextField(16);
form.add(emailText, gbc);
gbc.gridx = 0;
gbc.gridy = 3;
JLabel passwordLabel = new JLabel("Password");
form.add(passwordLabel, gbc);
gbc.gridx = 1;
passwordText = new JPasswordField(16);
form.add(passwordText, gbc);
gbc.gridx = 0;
gbc.gridy = 4;
JLabel confirmLabel = new JLabel("Confirm password");
form.add(confirmLabel, gbc);
gbc.gridx = 1;
confirmPasswordText = new JPasswordField(16);
form.add(confirmPasswordText, gbc);
gbc.gridx = 1;
gbc.gridy = 5;
c1 = new JCheckBox("I agree to websites rules!");
form.add(c1, gbc);
gbc.gridx = 1;
gbc.gridy = 6;
textArea = new JTextArea(2, 30);
textArea.setEditable(false);
textArea.setFocusable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
form.add(scrollPane, gbc);
return form;
}
private JPanel createHeading() {
JPanel heading = new JPanel();
JLabel label = new JLabel("REGISTRATION FORM");
label.setFont(label.getFont().deriveFont(Font.BOLD, 14.0f));
heading.add(label);
return heading;
}
private JPanel createRadioButtons() {
JPanel radioButtons = new JPanel();
ButtonGroup group = new ButtonGroup();
maleButton = new JRadioButton("Male");
maleButton.setSelected(true);
radioButtons.add(maleButton);
group.add(maleButton);
femaleButton = new JRadioButton("Female");
radioButtons.add(femaleButton);
group.add(femaleButton);
return radioButtons;
}
private void submit(ActionEvent event) {
textArea.setText("");
String name = nameText.getText();
textArea.append(name);
String gender;
if (maleButton.isSelected()) {
gender = "male";
}
else {
gender = "female";
}
textArea.append(", " + gender);
String email = emailText.getText();
textArea.append(", " + email);
String password = new String(passwordText.getPassword());
textArea.append(", " + password);
String confirmPassword = new String(confirmPasswordText.getPassword());
textArea.append(", " + confirmPassword);
textArea.append(", " + c1.isSelected());
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new Login().createAndDisplayGui());
}
}
- Usually you use a layout manager rather than setting it to null. Refer to Laying Out Components Within a Container
- You need to group
JRadioButton
s in aButtonGroup
to ensure that only one can be selected. Refer to How to Use Buttons, Check Boxes, and Radio Buttons - Method
getText
is deprecated forJPasswordField
. Refer to How to Use Password Fields. - I chose to display the user inputs in a
JTextArea
in aJScrollPane
but there are other options. Refer to Using Text Components and How to Use Scroll Panes. - Since Java 8, the
ActionListener
interface can be implemented via a method reference.
Related Topics
"Implements Runnable" VS "Extends Thread" in Java
Assigning Variables With Dynamic Names in Java
How to Create a Java String from the Contents of a File
Loop Doesn't See Value Changed by Other Thread Without a Print Statement
Convert a String Representation of a Hex Dump to a Byte Array Using Java
Why Do I Need to Override the Equals and Hashcode Methods in Java
How to Append Text to an Existing File in Java
Providing White Space in a Swing Gui
Stringbuilder VS String Concatenation in Tostring() in Java
How to Deal With "Java.Lang.Outofmemoryerror: Java Heap Space" Error
Connect Java to a MySQL Database
When Do You Use Java'S @Override Annotation and Why
What Is the Point of the Diamond Operator (≪≫) in Java
Android Activity Classnotfoundexception - Tried Everything
Add a Complex Image in the Panel, With Buttons Around It in One Customized User Interface
Android Update 17 Seems Incompatible With External Jars
How to Count the Number of Occurrences of a Char in a String