• 30天代码day3 Intro to Conditional Statements


    Boolean

    A logical statement that evaluates to true or false. In some languages, true is interchangeable(可互换的) with the number 1 and false is interchangeable with the number 0.

    Conditional Statements

    The basic syntax used by Java (and many other languages) is:

    if(condition) {
        // do this if 'condition' is true
    }
    else {
        // do this if 'condition' is false
    }
    

    where condition is a boolean statement that evaluates to true or false. You can also use an if without an else, or follow an if(condition) with else if(secondCondition) if you have a second condition that only need be checked when condition is false. If the if (or else if) condition evaluates to true, any other sequential statements connected to it (i.e.: else or an additional else if) will not execute.

    Logical Operators

    Customize your condition checks by using logical operators. Here are the three to know:

    • || is the OR operator, also known as logical disjunction.
    • && is the AND operator, also known as logical conjunction.
    • ! is the NOT operator, also known as negation.

    Another great operator is the ternary operator for conditional statements (? :). Let's say we have a variable, v, and a condition, c. If the condition is true, we want v to be assigned the value of a; if condition c is false, we want v to be assigned the value of b. We can write this with the following simple statement:

    v = c ? a : b;

    In other words, you can read c ? a : b as "if c is true, then a; otherwise, b". Whichever value is chosen by the statement is then assigned to v.

    Switch Statement

    This is a great control structure for when your control flow depends on a number of known values. Let's say we have a variable, condition, whose possible values are val0, val1, val2, and each value has an action to perform (which we will call some variant of behavior). We can switch between actions with the following code:

    switch (condition) {
        case val0: 	behavior0;
                    break;
        case val1:	behavior1;
                    break;
        case val2:	behavior2;
                    break;
        default: 	behavior;
                    break;
    }
    

    Note: Unless you include break; at the end of each case statement, the statements will execute sequentially. Also, while it's good practice to include a default: case (even if it's just to print an error message), it's not strictly necessary.

    Additional Language Resources
    C++ Statements and Flow Control
    Python Control Flow Tools

  • 相关阅读:
    利用Connect By构造数列
    Linux学习4——Vim和Bash
    Linux学习3——磁盘文件管理系统与压缩和打包操作
    Linux学习2——文件与目录
    Linux学习1——首次登录
    Linux系统的简介及Linux系统的安装
    Windows系统的安装
    5月份的技术总结
    计算机网络基本概念
    软件测试基础概念摘要
  • 原文地址:https://www.cnblogs.com/helloworld7/p/10454457.html
Copyright © 2020-2023  润新知