课程: Learning Java 17
Map program control flow
- [Instructor] In the last chapter, we looked at how we can represent data in Java using data types and variables. In this chapter, we're going to add some decision-making logic that allows our programs to have different outcomes. We saw this a little bit in the last lesson where we printed out whatever the user inputted. But this time, we'll create more sophisticated control flow using conditions. A program's control flow is the order in which the program's instructions are executed. All of the programs we've looked at so far execute one statement after the other. We create a variable and then print it. Or we create two variables and print them both. Each line of code was executed sequentially. Using special control flow statements, and conditions, we can manipulate which line of code is executed. A line of code might be never executed. It might be executed once, or it might be executed multiple times. The conditions determine how many times if at all, a given line of code is executed. Let's take a look at the control flow of a virtual fortune teller program. With the fortune teller, the user will pick a number between one and 10. Depending on the number the user picks, the user will receive a certain fortune. This diagram maps out the control flow of this program. It describes how we want the program to work. We start with the fortune teller asking the user to pick a number between one and 10. The circle represents the start, and the parallelogram represents input or output. The diamond represents a condition. Something that's true or false. And that condition determines which print statement is run. If the inputted numb is less than five, meaning the condition is true, the left lower block is run. If the inputted numb is not less than five, meaning it's equal to five or greater than five, the lower right block is run. Only one of the fortune teller print statements will run. Not both or neither. So we already know how to program some of this. We know how to output, pick a number between one and 10. We also know how to get access to the user's input, and save it to a variable. What we do not know is how to write or implement Java code for a decision block. We call these decision blocks or control flow statements because they make a decision. They decide which code statements to run on each execution of the program. In our case, the decision block is asking the question, if. With the condition, inputted numb less than five. Depending on whether the condition is true or false, meaning if inputted numb is less than five or not, a decision is made, and a given code statement will be run. Of course right now, this is just a diagram. It's a representation of how we want our program to work in Java. We can use this diagram as a guide to implement our Java program.
随堂练习,边学边练
下载课堂讲义。学练结合,紧跟进度,轻松巩固知识。