public class testBranch1 { public static void main(String args[]) { int myScore=96; if (myScore >= 90) System.out.PRintln("Very Good!”); if (myScore < 90) System.out.println(“make great efforts!”); } }
public class testBranch2 { public static void main(String args[]) { int myScore=96; if (myScore >= 90) { System.out.println("Very Good!”); } else { System.out.println(“make great efforts!”); } } }
大家可以看到,这个程序就可读了,假如myScore(“我的成绩”)大于或等于90,那么就打印“Very Good!”,否则(也就是说myScore不大于或等于90,即小于90)就打印“make great efforts!”。
从这个例子中,我们可以总结出if-then-else结构的if语句格式:
if (逻辑表达式) { 语句; } else { 语句; }
在本节中,我们学习了流程控制中最基本的一种:分支结构。在Java语言中,是使用if语句来实现的。
自测练习
1) 使用if-then-else语句,_______使用缩排。
a.不能 b.建议 c.必须 d.有时必须
2) 阅读以下程序,回答问题:
if (myScore >= 90) System.out.println("Congratulate to you!”); System.out.println("You score is very good!”); if (myScore < 90) System.out.println(“make great efforts!”);
§ 当成绩为50分时,程序还说“you score is very good!”,这说明这个程序不符合逻辑。应该改为:
if (myScore >= 90) { System.out.println("Congratulate to you!”); System.out.println("You score is very good!”); } if (myScore < 90) System.out.println(“make great efforts!”);
if (myScore >= 90) System.out.println(“better”); if ((myScore >= 80)&&(myScore<90) System.out.println(“good”); if ((myScore >= 60)&&(myScore<80) { System.out.println(“middle”); } else { System.out.println(“bad”); }
7.2 循环结构
7.2.1 while循环
实例说明
1.首先,我们使用文字编辑软件输入下源程序。
源程序:testLoop1.java
public class testLoop1 { public static void main(String args[]) { int counterLoop=8; while (counterLoop > 0) { System.out.println(counterLoop); CounterLoop - = 1; } } }
public class testLoop2 { public static void main(String args[]) { for (int counterLoop=8;counterLoop > 0;counterLoop--) { System.out.println(counterLoop); } } }
public class multiCase { public static void main(String args[]) { int myScope=89; int grade=myScope/10; switch(grade) { case 10: case 9: System.out.println(“Excellent!”); break; case 8: System.out.println(“Good!”); break; case 7: System.out.println(“Average!”); break; case 6: System.out.println(“Pool”); break; default: System.out.println(“Failure!”); } } }
switch(grade) { case 10: case 9: System.out.println(“Excellent!”); break; case 8: System.out.println(“Good!”); break; case 7: System.out.println(“Average!”); break; case 6: System.out.println(“Pool”); break; default: System.out.println(“Failure!”); }
public class switchLianxi { public static void main(String args[]) { char myScope=’B’; switch(myScope) { case ‘A’: System.out.println(“Excellent!”); break; case ‘B’: System.out.println(“Good!”); break; case ‘C’: System.out.println(“Average!”); break; case ‘D’: System.out.println(“Pool”); break; case ‘E’: System.out.println(“Failure”); } } }