And yes I know most of you know this.
To receive user input,
You need to import something and it is-
import java.util.Scanner
Let's do a simple program.
Tip: I use NetBeans, and Eclipse is also recommended.
package userinput;
import java.util.Scanner;
public class UserInput {
public static void main(String[] args) {
That will be the basic.
Scanner user_input = new Scanner(System.in);
A piece of code we need to create a Scanner to take user inputs.
String first_name;
We start creating a string
System.out.print("Enter your first name: ");
Now we need the user to type, and note that we are using
System.out.print instead of
System.out.println so that the user will type on the same line.
Now we create the code to receive input from user, which is
first_name = user_input.next();
Note: Without
Scanner user_input = new Scanner(System.in), the code above would
not work.
Now we proceed, requesting the user to input the second part.
String family_name;
We create the string, again.
System.out.print("Enter your family name: ");
Now we change the
first name to
family name.
Proceeding, we create the code to receive input from user, needed for everything
String.
family_name = user_input.next();
Note that we are using family_name instead of first_name as the one we type must be similar to the one in the
String.
Now we are ready to combine the names into
one. Similarly, we use
String.
String full_name
Now we combine them.
full_name = first_name + " " + family_name;
Tip: After every line of code, there must be a
;(Semi-Colon).
Now we are ready to show the full name, by using
System.out.println("You are: " + full_name);
Thanks for your attention! Hope this helped!
Bonus:
The full piece of code:
package userinput;
import java.util.Scanner;
public class UserInput {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String first_name;
System.out.print("Enter your first name: ");
first_name = user_input.next();
String family_name;
System.out.print("Enter your family name: ");
family_name = user_input.next();
String full_name;
full_name = first_name + " " + family_name;
System.out.println("You are: " + full_name);
}
}
Note: I'm sorry but it seems like that I
cannot put appropriate spaces for the bonus.
Do inform me of any errors!
