程序结构
结构化编程只有三种结构:
顺序,选择和迭代。
选择允许选择程序中的路径。
if语句如果(条件)
然后操作
例如用伪代码
if month is October
then write "new term"
if month is June
then write "exams!"
这可以扩展为包括else子句:
一个)
if mark is greater than or equal to 40
then write "pass"
else write "fail"
进一步说明:
b)[代码]
如果标记大于或等于70
然后写“辉煌”
否则,如果标记大于或等于40
然后写“通过”
否则写“失败” [代码]
缩进 :将if 对齐 。缩进使含义更清楚。 否则将排队以匹配它所属的。
假设标记是int
一个)
if (mark>=40)
System.out.println("pass");
else System.out.println("fail");
b)
if (mark>=70)
System.out.println("brilliant");
else if (mark>=40)
System.out.println("pass");
else System.out.println("fail");
比较运算符为:
<<=>> = ==!=
一个使用扫描仪从键盘和if-then-else读取数据的程序:
import java.util.*;
public class Ifmarks
{
public static void main(String args[])
{
Scanner keyboard=new Scanner(System.in); // open Scanner
final int PASS = 40;
final int DISTINCTION = 70;
System.out.print("type a mark: ");
int mark = keyboard.nextInt(); //read an integer
if (mark>=DISTINCTION)
System.out.println(" brilliant");
else if (mark>=PASS)
System.out.println(" pass");
else System.out.println(" fail");
}
}
在这里,我们还看到了常量的使用:如果一个值不变,则可以将其声明为一个常量,按照惯例,该常量以大写形式编写。
这样做的好处是,如果常数发生变化(例如上面的区别标记),则只需更改一次,而不必在大型程序中编辑多个事件。
通过包含在{}中,可以在if的分支上放置多个语句。 例如,假设i为int,则表示它是0,正还是负,以及如果负则改变其符号
if (i<0)
{
System.out.println("i is negative, inverting");
i=-i;
}
else
if (i==0) System.out.println("zero");
else
{
System.out.println("i is positive");
System.out.println("no change");
}
else对应的if和{}垂直排列
From: https://bytes.com/topic/java/insights/641527-program-structures