Java Lesson 3 | Input
Hello, this is Jake. I'm a special guest on Maads 101. This is going to be my third Java tutorial and I'm going to be doing this one on user input. So let's open up Eclipse.
All right, so in the last tutorial we made variables like int i = 10;
and in the program I assigned it a value of 10. Now what we're going to be doing here is we're going to be assigning variables the value of whatever the user is going to input. So in order to do that we have to get the Scanner and we don't already have that, so we have to import it.
So to do this, we type import java.util.Scanner;
and if I wanted everything from util, I would just do that as is. But I don't need everything since I'm only going to be using the Scanner from it.
All right, so what we're going to be making here is a program that asks the user to enter their name. Then it's going to store that name in a string variable and then it's going to output "Hello" plus that string. So it'll be like, "Enter your name, Jake. Hello, Jake."
All right, so first I'm just going to make a prompt so they know to enter their name. I already went over this stuff, so actually I'll make that print
because I don't want them to print it on the next line. Just because it doesn't really matter though.
So next thing we have to do is create a string to store that name. All right, so now that we have that, we're going to start getting to the meat of this tutorial.
Um, to use a Scanner we have to create a Scanner object. So to do this you type Scanner
(capital S) and you can name it whatever you want, scan = new Scanner(System.in);
.
What that did is it created a scanner object that's going to allow us to get input from the keyboard. Um, so yeah, and that's probably going to be confusing right now but you'll understand it eventually. In a few more tutorials, I'll be going in more depth about objects and things like that.
So first thing we're going to do is we do name =
, and what we're going to be doing is we're going to be setting it equal to whatever they input. So do scan.next();
and for strings you just do next()
with those empty parentheses.
So what that would do is it would set name
to whatever they entered. And next, for strings, if it was an integer I do nextInt()
, nextDouble()
for doubles, and so on and so forth. But just next()
is for strings.
And now System.out.printLn("Hello " + name);
. So I'm just going to run this to show you what it does: "Enter your name." J in here, Jake. "Hello, Jake."
See? So what that did is it asked me to enter my name, and when I entered my name I used a scanner object to get the input, and then I set the name equal to that input, then printed out "Hello" plus whatever they inputted.
So that is some input for you guys. So see you later!