What does the code do?
The java code below asks the user to input their name and age and outputs the results in the console window.
import java.util.Scanner;
public class UserInput {
public static void main (String[] args) {
Scanner uin = new Scanner(System.in);
System.out.println("What is your name?");
String name = uin.nextLine();
Scanner uia = new Scanner(System.in);
System.out.println("How old are you?");
int age = uia.nextInt();
System.out.println("Hello " +name+ ", you are "+age+ " years old.");
}
}
Create a new file then copy and paste the code above
Save the file as UserInput.java
Next open the terminal, and enter the following command to compile the file
javac UserInput.java
A new file named UserInput.class will be created
To execute the code enter the following command
java UserInput
As I'm learning Java, I will try my best to explain what's going on in the code. Getting the terminology right is sometimes harder than the actual coding itself.
To get user input in Java we need to import the Scanner class. import java.util.Scanner;
We create new Scanner objects and then assign them to variables. String for characters, Int for numbers.
Scanner uin = new Scanner(System.in); String name = uin.nextLine();
Scanner uia = new Scanner(System.in); int age = uia.nextLine();
We then output the results by using System.out.println. To output the variables we use +name+ and +age+