Lesson 05

条件 与 分支Conditions and Branches

if 语句If Statements

变量作用域Variable Scopes

是什么

决定变量的有效范围

规则

出生:变量声明

死亡:撞到所包含它的最近的回大括号

命名重名

变量命名时,不能跟任何现在可以接触到的变量同名

继续挑战

增加新规则

如果金额 达到 200 元

就 - 40

< < < <
商品总价:200 元 优惠:40 元物流费:免费订单总价:160 元

图格子的故事

三目运算符

样本

使用前
1 2 3 4 5
if (x < 0) { a = -1;} else { a = 1;}
特性

if else

都是一赋值语句

给同一个变量

使用后
1
a = x < 0 ? -1 : 1;

语法

模板
<condition> ? <expression1> : <expression2> ;
样例
1
x *= x < 0 ? -1 : 1;

Switch 语句

样本

使用前
1 2 3 4 5 6 7
if (x == 0) { ...} else if (x == 1) { ...} else if (x == 2) { ...}
特性

if else

都是等于比较

比较一边是一样的变量

另外一遍是字面量

比较的是原类型

使用后
1 2 3 4 5 6 7 8 9 10 11
switch (x) { case 0: ... break; case 1: ... break; case 2: ... break;}

语法

模板
switch (<variable>) {
    case <value1>:
        <statement>
        ...
        break;
    case <value2>:
        <statement>
        ...
        break;
}

下滑Fall Through

可以不写 break

就会逐句执行, 直到遇见 break

default

可以写 default:

起到 else 的效果

内存 与 程序调试Memory and Debugging

人工内存

是什么

模拟计算机处理代码的过程

目标

没有运行代码,但已经在脑子里运行了这个代码

要求

你需要知道 计算机是 如何运行代码

你需要知道 在任何一个时间

都有哪些变量活着

并且 这些变量的值 都是多少

样例

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
package course.lesson05.case02_ex; import io.zzax.jadeite.console.Console; public class Solution { public static void main(String[] args) { int price = Console.readInt(); Console.println("商品总价:" + price + " 元"); int total = price; // 满 200 减 40 if (price >= 200) { int discount = 40; total = price - discount; Console.println("优惠:" + discount + " 元"); } // 满 100 免 运送费 if (price >= 100) { Console.println("运送费:" + "免费"); } else { int shippingFee = 6; // 不要动它 total = price + shippingFee; Console.println("运送费:" + shippingFee + " 元"); } // 显示支付 Console.println("您需支付:" + total + " 元"); }}
Line    total   payment             io
7       197                         >   197
8       |                           <   总价:197 元
10      |       197
13      |       |                   =   false
20      |       |                   =   true
21      |       |                   <   运送费:免费
29      |       |                   <   您需支付:197 元    

程序调试

检查点

在某些位置输出信息

运行后,在控制台检查是否显示,从而证明这一行有没有执行

1 2 3 4 5 6
...if (...) { Console.println("Check Point 1"); ...}...

输出数据

在某些位置输出信息

运行后,在控制台检查是否显示,从而证明这一行有没有执行

1 2 3
int a = 0;a = ...;Console.println("a: " + a);

Debug 模式

增加断点

在行号 右边,可以点一下,会点出一个粉刺

就是断点

进入 debug 模式

点击 小三角,出来的菜单里,点击 Debug

之后就可以进入 debug 模式

debug 模式

debug 模式下,程序运行到 断点处,就会暂停

控制面板

检查数据

小跳跃按钮 下一行

继续播放按钮 继续执行

红色方块按钮 结束执行

ZZAX 微信公众

文档一更新,立刻告诉你