一、顺序结构
代码从主函数开始依次向下运行。
也是一种宏观的代码运行结构。
double r,h,s,v;//定义半径为r,高为h
System.out.println("Enter the radius and length of a cylinder:");
Scanner in = new Scanner(System.in);
r=in.nextDouble();
double p = 3.1415926;
s = p*r*r;
System.out.println("The area is " + s);
h = in.nextDouble();
v = s * h;
System.out.println("The volume is " + v);
像这样先定义r h s v,然后提示用户输入这个圆的半径也就是r,再依次输出面积和体积。
二、选择结构
1、if语句
基本表现格式为:
if (条件表达式 ){
当条件为true时执行的代码。
}else{
当条件为true时执行的代码。
}
即可以有:
if (a > 2) {
System.out.println("年轻是美好的");
}
表示的是:如果a>2 就执行年轻是美好的;如果是一个a<=2就直接跳出。
double x = (e * d - b * f) / (a * d - b * c);
double y = (a * f - e * c) / (a * d - b * c);
if (a * d == b * c) {
System.out.print("The equation has no solution");
}else {
System.out .print("x is " + x +" and y is" +y );
}
表示的是:如果 (a * b == b * c)就执行The equation has no solution
其余的不满足(a * b == b * c)这个条件的都执行x is " + x +" and y is" +y
2、嵌套if语句
嵌套if-else基本格式
if(条件1){
满足条件1的代码;
if(条件2){
满足条件2的代码;
}else{
不满足条件2时的代码;
}
}else{
不满足条件1的代码;
}
即可以有:
int max;
if (a > b) {
if (a > c) {
max = a;
}else {
max = c;
}
}
else {
if (b > c) {
max = b;
}else {
max = c;
}
}
System.out.println(max);
这是一个三个数比大小的代码。
if-else-if形式
if-else-if形式
if(条件1){}else if(条件2){
}else if(条件3){
}else{
}
……
即可以有:
if (d > 0) {
double x = 1.0e6;
r1 = (int)( r1*x)/x;
r2 = (int)(r2*x)/x;
System.out.print("The equation has two roots "+r1+"and"+r2);
}
else if (d == 0) {
System.out.print("The equation has one roots "+(int)r1);
}
else {
System.out.print("The equation has no real roots ");
}
3、switch语句
switch(变量){
case值1:
执行语句1;
break;
case值2:
执行语句2;
break;
case值3:
执行语句3;
break;
……
default;
执行语句n;
break;
}
4、switch语句与if语句的不同
if它既可以对一个单一的值进行判断,也可以对一个区间的值进行判断。
即:if else 与if else if
switch只能判断单一的值
switch所要求的变量的数据类型:byte short int char String 枚举
三、循环结构
主要是为了解决重复执行的代码
已知循环次数的用for循环
for (i = 1;i <= 6;i++)
这是一个初始值为1,总共循环6次的一个循环体。
不知重复次数但是已知结束条件的循环:用while循环。
do {
sum = sum + num % 10;
num = num / 10;
}while(num != 0);
System.out.println("The sum of digits is"+ sum);
这是一个求每一位数之和的题,在不知道这是一个几位数的情况下每次对个位数字进行取余,然后依次删除掉每一次的个位数字,直到这个数变为0为止。
循环体:就是我们需要被多次循环执行的代码块