课程: Learning Java 17
Defining functions in Java
- [Instructor] To use a function in Java, we have to define it first. For the Make PB&J Sandwich function, we had to define the steps needed to accomplish the given task, make a peanut butter and jelly sandwich. For Announce Teatime, we had to define the steps to announce teatime. It's important to that just because we're defining a function doesn't mean we're using it. Just because I've given you the instructions on how to make a PB&J does not mean you've actually made the sandwich. This means the way we'll write this code will be a little different than the things we've written previously. Let's try implementing our Announce Teatime function in Java. To define this function, we're going outside of the main function for the first time. Everything we've done so far has been about executing code, not defining new functionality that could potentially be used. To define the new series of steps that we want associated with Announce Teatime, we'll go just above the main function and write public static void. Then, we'll label our function Announce Teatime. We won't be covering what the keyword public means in this course, but we will look at static and void later on. The name of our function is Announce Teatime. We'll follow this up with some open-close parentheses and then some open-close curly brackets. We'll talk about the open and close parentheses in a later lesson, but for now, we're going to put the steps for our function in between the curly brackets. These will be the lines of code that will be executed when our function is used. Thinking back to the steps we laid out before, the first step is to wait for teatime. To keep this as simple as possible, we're going to make our program pause until the user types in a random word and presses Enter on their keyboard. There are other ways we could implement this waiting for teatime step, but this is the most straightforward with what we know so far. For this function, once the user types in a random word and presses Enter, we'll announce teatime. Let's tell the user to type in a random word and press Enter. To check if the user has entered a word in the console, we'll need to create a scanner. Then, we can use the next operation as we've done before. We won't need to reference or use the random word that the user enters, so we just write input.next. We don't need to save it in a variable. Finally, let's announce teatime. It's teatime. Awesome. We just defined our first function. The function name is Announce Teatime and it has five step or five lines of code to execute. With our function defined, we can now use it in our program.
随堂练习,边学边练
下载课堂讲义。学练结合,紧跟进度,轻松巩固知识。