Start course
Difficulty
Intermediate
Duration
2h 7m
Students
369
Ratings
4.8/5
Description

This course explores the fundamentals of Java and puts them to use with some real-life examples looking at an average of three program and a mad libs project.

Learning Objectives

  • Learn how to print information out to the user, how to create and use variables, values, and constants, how these things have data types, and the differences and similarities among the data types
  • Learn about arithmetic, relational, and logical operators
  • Understand how to obtain input from the user of our programs

Intended Audience

  • Beginner coders or anyone new to Java
  • Experienced Java programmers who want to maintain their Java knowledge
  • Developers looking to upskill for a project or career change
  • College students and anyone else studying Java

Prerequisites

This is a beginner-level course and can be taken by anyone with an interest in learning about Java.

Transcript

In the previous lecture, we rounded out our exploration of the three major categories of operators in Java with Logical operators. As a reminder, the three major categories of operators are Arithmetic, Relational, and Logical. All of these are essential for performing mathematical and decision-based operations throughout our code. In this lecture, we will expand our knowledge by adding user input to our toolbox. We already know how to send output to the console using the standard output stream: System.out. We have used println extensively and also discussed the print method which is like println but doesn't insert a newline character into the standard output stream. 

We've used data throughout this section in the form of variables, symbolic constants, and values (typically in the form of literal constants). However, the data was hardcoded; meaning that we wrote the values directly into the course code. Although hardcoded data is something that we commonly use, we also want to be able to obtain data from outside of our application, for instance, from the user. The standard input device for most users is the keyboard and that is what we will be obtaining data with, using the standard output stream object: System.in. So, let's create KeyboardInput file and the main skeleton.

So, under 'src', we right click that and go to 'Java Class', then we'll call this KeyboardInput. Now, we'll go in here, public static void main(String[ ] args) { }//end main. Now we have to use again the standard input stream object, System.in. Since System.out is the standard output stream object, System.in is the corresponding object used for input. It's very organized. However, we will use the standard input object with a class I'm going to introduce you to, called Scanner. I'll write some code, and then we will discuss it. So, we need import java.util.Scanner; at the top. And I'll explain what all this means in just a moment. We create a Scanner. I'll call the variable keyboard = new Scanner(System.in);  standard input object in between the parenthesis, String name; System.out.println("What is your name?"); and then we will put name = keyboard,  which is out Scanner object,  .nextLine(); and then finally, I'm going to put System.out.println("Hello, " + name);, and of course, let's run it.

So, 'KeyboardInput', right click, and then I'm going to go down to 'Run 'KeyboardInput.main()''. Here's our output. You'll notice that it's pausing after it says, "What is your name?" because it's waiting for me to enter some sort of data. So, I'm going to say, John Baugh. Then it just echoes to me: Hello, John Baugh. So, now we can send data into our programs, which we say is at runtime. The first important aspect that you may note is the necessity of importing the Scanner class using java.util.Scanner here at the top. The java.util portion right here is called a package in java, which is really just a collection of classes and occasionally, other things like interfaces which we will discuss later in the course. Well, you haven't typed anything related to packages in our files yet. There is a package that is imported automatically in every program that we create, it is java.lang; L-A-N-G for the Java language. This is the default package. So, this is where classes like String live. Scanner doesn't live in java.lang. So, we have to explicitly import it.

This makes the code easier to write. If we didn't import it, we'd have to do this. So, I'm going to comment out this import statement briefly, and I'm going to show you what you will have to do. You'll notice that Scanner immediately turns red because it doesn't know what Scanner is, but you'd have to type java.util in front of Scanner, each occurrence, java.util.Scanner. So, usually we want to take advantage of import statements. So, notice that we've created this variable of type Scanner which I can just restore now. I'll just put this, delete that right there. So, I've uncommented this. So, now it sees java.util.Scanner. So, anytime it sees Scanner, it knows we're talking about that class that lives in java.util. So, again, notice that we have this variable whose data type is Scanner, and we've named it keyboard. So, that's the identifier. And then, we set it equal to new Scanner and then passed System.in as the argument to the constructor of Scanner. Well, string has a special place in java and this is usually not necessary for Strings. With any other class, you will write the new statement followed by the class's constructor and any necessary arguments.

For now, the constructor is just code that is executed to create or construct an object, in our case, of type Scanner. The constructor has the same name as the class. For the Scanner constructor, in this case, we pass in a single argument: System.in, which we already learned was the standard input object. So, using the scanner and telling it to scan standard input because you could tell it to scan other things, which we'll get to later in the course. We can get data from the user. Now, we prompt to the user, and prompting means we just ask them for something so they know what to do; they know they're supposed to do something. Then, we call the nextLine method of the Scanner class. We call it on our keyboard variable so that we can get the String that the user types. Now, since it says nextLine, it's going to basically read-in everything up to the very end of the line until you hit Enter. So, we finally print out a greeting to the user with their name. So, the nextLine method will read-in entire lines of Strings, not just single words. In fact, it will read whatever you type until you hit the Enter key.

We say that once the nextLine method encounters the newline character (created by hitting Enter or Return), that this character is consumed (which means it's removed from the input stream), and then the method terminates, or ends. So, these input streams are like a stream with salmon or fish in it. So, they're floating around, and swimming, and everything, and anything you pull out that's consuming it. Now, in the case of nextLine, we're actually making use of what we typed John Baugh, but it actually discards or consumes the enter, the newline character. So, what happens if we want to read-in say, an integer instead of a String? A good option is to use the nextInt method. Let's update our code and see what happens. So, we're going to just to keep it organized. Keep the variable declarations up here and under this prompt for the name, I'm going to put System.out.println("What's your age?") and then I'm going to put age = keyboard. Now this time, notice there's a lot of stuff you can get. nextInt is the one that I want and then finally, near the bottom, system actually will put it afterwards since we asked for it afterwards. So, we've got the name printed out first. Now, we can say ("age is " + age). So, let's run this and see what happens.

Right click, 'Run 'KeyboardInput.main()''. What's your name? I'll just put John this time. What's your age? 37. It will say, "Hello, John, age is 37". Now, what happens if we ask for the city after we asked for the age? Let's add some code and see if something interesting happens. So, up here, I'm going to put the String city just to keep the strings together, don't have to, but I'll put String city there. Now, I'm going to do this in a particular order on purpose because we want to see if something interesting will happen that will help us learn here. ("What city do you live in?") Notice, I'm putting this code right underneath where I prompted and obtained the age. So, the city comes last. So, you've got prompting for a String, prompting for an Int, and then prompting for another String. Finally, at the bottom, I'm going to print out the ("city is " + city); So, let's see what happens now when we run the application. Right click, 'Run 'KeyboardInput.main()''. What is your name? John. What's your age? 37, and that says, "What city do you live in?" but then it completes, and it prints out all this. So, what happened there?

It didn't even stop to let us enter the city. So, what's going on? Well, this is a common bug in a lot of applications that has caused many students as well as some professionals  - sleepless, tear-filled nights. So, I'm going to try to save you from such a fate by explaining what's happening. First, you should have a basic idea of what I mean when I say "stream". This is again, I'm going to reiterate that you can think of a stream a little bit like a stream of water with fish in it. The analogy isn't perfect, but it should suffice. The fish in the stream of water are like the different characters that are read in from the keyboard when the characters are removed from the input stream. They are either used in some way or discarded. It would be a little bit like capturing fish and either keeping them or disposing of them in some way.

So, I said that the nextLine method consumes the newline character;  that is, the character generated by you hitting the Enter or Return key. This means that the string of characters in front of the newline character is returned by the nextLine method, and then the newline character is pulled out of the input stream and discarded. So, it's not in the stream anymore. But nextInt works a little bit differently. It pulls numeric data representing an imager or integers out of the input stream, but it ignores the newline character leaving it in the input stream. So, what happened in our code where the program didn't wait for me to enter data in from the keyboard for the city? 

Well, since we're asking for the age, an integer, right before the city, the newline character that was generated when we hit Enter after hitting the age is left in the stream. Then, when we get to the nextLine just below it, the newline character is detected by that nextLine and it thinks you're done typing and it throws out that newline character and discards it, but it didn't wait for you to put any input. Therefore, we have this tiny problem. You could just move your prompts around and ask the strings up front, and then the numeric data later, but that's not ideal. We might want to ask for some interspersed strings, integers, and other types of data. So, what do we do to fix this then? Well, you can call the nextLine method anytime you ask for numeric data like the integer after it, of course. So, then the new line character gets consumed and discarded and the input can continue normally. So, let's fix our code. So, right after we get the nextInt here, I'm going to put another keyboard.nextLine() right there. Let's run the code. Right click and you will notice that we go to 'Run 'Keyboardinput.main()'' and it will say, what is your name? John;

what is your age? 37;  and what city do you live in? I'll say Dearborn and then it will say, Hello, John; age is 37; and city is Dearborn. It actually waited this time. So, it seems like it's working a lot better now. Whenever you are taking non-String input like nextInt, you should also put an extra call to nextLine underneath it to consume the newline character. Just get in the habit of doing that and you'll be in a lot better position in the future. Now, you'll also notice that I'm not obtaining the value. I'm just calling this method. I'm not doing like I did here because I'm not interested in getting any data back from it. I just want to get that newline out.

So, this is consume the newline. Note that in addition to nextInt, we also have other methods such as nextDouble, nextByte, nextBoolean, and many others. So, for a little bit of practice with what I just said, I have a challenge for you using this same keyboard input class, write code to prompt and obtain a real number; one that may include decimals from the user. Multiply that value by two, and then print the result to the console before the name of the city is obtained. So, pause the video. Come back when you're done or if you need some help. How did that go for you? Were you able to accomplish this challenge? This one had some tricky parts to it - and required you to do a little bit of extrapolation using what you know so far to figure out some syntax we haven't explicitly practiced. So, let's do it together. I'm going to somewhere up here, and it didn't really matter what you named it as long as you give it a good name and a valid name. So, I'm going to call it dubInput for double and below where I'm asking for the age, what I'm going to do is I'm going to say System.out.println("What's your real number?").

I didn't really specify what that real number was. So, we're just going to ask for what is the real number. It's going to say keyboard.nextDouble(), which is what we want, and then we need to consume the newline character. Big hint. And then we have to double the value of dubInput. Now we've got different ways to do this and if you remember one of the ways, dubInput * = 2, which is equivalent to dubInput = dubInput * 2. That would be either of those ways would work to double the value. Remember this is a shortcut, the compound assignment operator, compound multiplication assignment operator in this case. Now, once we've done that, we do want to print this out near the bottom, under city is I'm going to say System.out.println. I'll say twice your number is and then just put dubInput. There we go. Now as always, let's run it. Right-click, 'Run 'KeyboardInput.main()''. What's your name? That's John; age is, we'll just say 21 this time, wishful thinking. 3.5 is my real number. What city do I live in? We will say Lincoln Park. Here we go. So, it says Hello, John; age is 21; city is Lincoln Park. Twice your number is 7.0. Nice work, everyone. I hope you enjoyed this little challenge. The next lecture is our first section project. I'll see you there.

 

About the Author
Students
1741
Courses
20
Learning Paths
4

John has a Ph.D. in Computer Science and is a professional software engineer and consultant, as well as a computer science university professor and department chair.

Covered Topics