145k views
1 vote
How usually get input from the keyboard in java? Explain using simple example?

User Roth
by
7.9k points

1 Answer

6 votes

Answer:

In Java, one common way to get input from the keyboard is by using the `Scanner` class from the `java.util` package. The `Scanner` class has various methods for getting different types of input such as `next()`, `nextLine()`, `nextInt()`, `nextDouble()`, etc.

Here's a simple example:

```java

import java.util.Scanner; // Import the Scanner class

public class Main {

public static void main(String[] args) {

Scanner myObj = new Scanner(System.in); // Create a Scanner object

System.out.println("Enter your name:");

String userName = myObj.nextLine(); // Read user input

System.out.println("Your name is: " + userName); // Output user input

}

}

```

In this example, we first import the `Scanner` class. Then, in the `main` method, we create a `Scanner` object called `myObj` and pass `System.in` as an argument to tell the Java compiler that we want to input something from the keyboard (system input stream).

We then print a message to the user, asking for their name. The `nextLine()` method is then used to read the input provided by the user.

Finally, we print the user's input back to them, demonstrating that we've successfully captured and stored their input.

This example is for reading a line of text (String input). If you want to read a number (like an integer or a double), you could use the `nextInt()` or `nextDouble()` methods instead of `nextLine()`.

User Jose Jet
by
7.9k points

No related questions found