zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    虚拟机安装CentOS不能联网的解决
    64位openSUSE12.3最完整的安装QQ的方法
    打水井
    一个阶乘中末尾零的个数
    DiscuzX开发手册【精品】
    一个获取PHP消耗时间的小函数
    php获取本月的第一天与最后一天
    在博客园创建了一个自己的博客~
    ie6 fixed 很纠结~这个js就解决了
    现在各个网站都在使用瀑布流布局吧~
  • 原文地址:https://www.cnblogs.com/helloworld7/p/10454457.html
Copyright © 2011-2022 走看看