第十四课 基本程序结构
程序的基本结构包括:顺序、分支和循环,顺序结构是指程序从上执行到下,这是总的结构形式,那么我们说的如果……那么……即为分支结构,而我们当反复的执行某种语句的时候则为循环结构。
注:在C语言中,可以在嵌套块中定义相同的变量,而在JAVA中是不允许的。
一、分支结构:
1、IF(条件表达式)
语句或语句组;
[ELSE
语句或语句组;]
这种语句我们以前用了不少,现在我们再举个例子:
要求从键盘输入学生成绩,输出相应的等级:
import javax.swing.*;
public class ifTest{
public static void main(String args[]){
String f=JOptionPane.showInputDialog("please input your grage:");
int g=Integer.parseInt(f);
if (g>=60){
if (g>=90)
System.out.println("优秀");
else
System.out.println("及格");
}
else{
if (g>0)
System.out.println("不及格");
else
System.out.println("缺考");
}
System.exit(0);
}
}
2、switch(表达式)
{
case 常量:
[语句或复合语句;]
[break;]
case 常量:
[语句或复合语句;]
[break;]
……
[default:
[语句或复合语句;]]
}
我们还是继续上面的例子来改装一下:
import javax.swing.*;
public class switchTest{
public static void main(String args[]){
String f=JOptionPane.showInputDialog("please input your grage:");
int g=Integer.parseInt(f)/10;
switch(g)
{
case 10:
case 9:
System.out.println("优秀");
break;
case 8:
case 7:
case 6:
System.out.println("及格");
break;
case 5:
case 4:
case 3:
case 2:
case 1:
System.out.println("不及格");
break;
default:
System.out.println("缺考");
}
System.exit(0);
}
}
第十四课 基本程序结构
最新推荐文章于 2021-04-07 22:00:57 发布