How to take input from user in Java?

Member

by rollin , in category: Java , 2 years ago

How to take input from user in Java?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by emely , 2 years ago

@rollin use Scanner to take input from the user in Java, code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.print("Your Name:");
        Scanner scannner = new Scanner(System.in);

        String name = scannner.next();

        System.out.println("Hello " + name);
    }
}


by lily.simonis , a year ago

@rollin 

In Java, you can take input from the user using the Scanner class.


Here's an example program that takes input of the user's name and age:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("What is your name? ");
        String name = scanner.nextLine();

        System.out.print("What is your age? ");
        int age = scanner.nextInt();

        System.out.println("Your name is " + name + " and you are " + age + " years old.");
    }
}


In the above program, we first create an object of the Scanner class and pass the standard input stream (System.in) to its constructor.


Next, we use the nextLine method to read the user's input for their name, and store it in a String variable named name.


Then, we use the nextInt method to read the user's input for their age, and store it in an integer variable named age.


Finally, we print out a message that includes the values of name and age.


Note: When using the nextInt method, the scanner will leave the newline character ( ) in the buffer, which can cause issues if you try to read a String after reading an integer. To avoid this, you can use the nextLine method after nextInt to consume the leftover newline character.

1
2
int age = scanner.nextInt();
scanner.nextLine();


Or, you can use the Integer.parseInt method to convert a String input to an integer value.

1
2
String ageString = scanner.nextLine();
int age = Integer.parseInt(ageString);