JAVA Syllabus
QUESTIONS & ANSWERS

How to use Scanner class to read input from the keboard in Java?

To use the Scanner class to read input from the keyboard in Java, you can follow these steps:

  1. First, you need to import the Scanner class by importing the package at the beginning of your Java program:
  2. Next, create a new Scanner object that will be used to read input from the keyboard:
  3. Once you have created the Scanner object, you can use it to read input from the keyboard by calling one of its methods. The most commonly used method is the nextLine() method, which reads a line of text input from the keyboard:
  4. You can then use the value of userInput in your Java program as needed.

    Here is an example Java program that uses the Scanner class to read input from the keyboard and then prints out the input:
    import java.util.Scanner;
    
    public class KeyboardInput {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            System.out.print("Enter some text: ");
            String userInput = scanner.nextLine();
            System.out.println("You entered: " + userInput);
        }
    }
    

    When you run this program, it will prompt the user to enter some text, and then it will print out the text that the user entered.

06/03/2023, 11:24 am Read : 267 times