Read User Input Java with Scanner Class


/ Published in: Java
Save to your folder(s)

This snippet will allow you to read user's input when they write in the console. This method uses the Scanner class, which is my favorite way of doing instead of using the Buffered Reader, with the Scanner, you can also read from a file.


Copy this code and paste it in your HTML
  1. import java.util.Scanner;
  2. public class ReadUserInput {
  3.  
  4. public static void main(String[] args) {
  5.  
  6. Scanner sc = new Scanner(System.in); //Creates the scanner and tells it
  7. //to read from the keyboard(System.in)
  8. String name; // The variable which is going to store the user's input
  9. System.out.println("Enter your name.");
  10. name = sc.nextLine(); //Sets name equal to user's input
  11. //if you just call the "next" method, the Scanner will read up to the first space.
  12. System.out.println("Hello " + name);//Greets the user
  13.  
  14. }
  15.  
  16. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.