Java的if、switch选择结构、循环结构
if选择结构
代码样例:
package com.struct;
import java.util.Scanner;
public class SunXvDemon01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入成绩");
int score = scanner.nextInt();
if(score>60){
System.out.println("成绩合格");
}else {
System.out.println("下学期补考");
}
scanner.close();
}
}
输出结果:
请输入成绩
80
成绩合格
switch选择结构
代码样例:
package com.struct;
public class Doment02 {
public static void main(String[] args) {
String name = "江西";
switch (name){
case "北京":
System.out.println("北京");
break;
case "上海":
System.out.println("上海");
break;
case "江西":
System.out.println("太美了");
break;
default:
System.out.println("其他地方");
}
}
}
输出结果:
太美了
循环结构
while循环
代码样例:
package com.struct;
public class WhileDoment01 {
public static void main(String[] args) {
int i = 0;
int sum = 0;
while(i<=100){
sum=sum+i;
i++;
}
System.out.println(sum);
}
}
输出结果:
5050
do····whlie循环
即使条件不满足但是我们也得执行一次
代码样例:
package com.struct;
public class DoWhileDmen01 {
public static void main(String[] args) {
int a =0;
do{
System.out.println(a);
a++;
}while(a<0);
}
}
输出结果:
0
for循环及例题
- for循环语句是支持迭代的一种通用结构,是最有效、最灵活的循环结构
1、计算0到100的之间的奇数和偶数和
代码样例:
package com.struct;
public class ForDomen01 {
public static void main(String[] args) {
int sum = 0;
int and = 0;
for (int i = 0; i < 100; i++) {
if (i%2!=0){
sum=sum+i;
}
else{
and = and+i;
}
}
System.out.println("奇数的和:"+sum);
System.out.println("偶数的和:"+and);
}
}
输出结果:
奇数的和:2500
偶数的和:2450
2、用while或者for循环输出一到一千之间能被五整数的数,并且每行输出三个;
注:System.out.printIn();中的In是换行的意思,把In去掉的话就代表不换行;
代码样例:
package com.struct;
public class SunCu {
public static void main(String[] args) {
//用while或者for循环输出一到一千之间能被五整数的数,并且每行输出三个;
for (int i = 0; i < 1000; i++) {
if(i%5==0){
System.out.print(i+"\t");
}
if(i%(5*3)==0){
System.out.println();
}
}
}
}
输出结果:
5 10 15
20 25 30
35 40 45
50 55 60
3、打印九九乘法表
代码样例:
package com.struct;
public class DaYing {
public static void main(String[] args) {
for(int i=1; i<=9; i++){
for(int j=1; j<=i; j++){
System.out.print(i+"*"+j+"="+(i*j)+"\t");
}
System.out.println();
}
}
}
输出结果:
1*1=1
2*1=2 2*2=4
3*1=3 3*2=6 3*3=9
4*1=4 4*2=8 4*3=12 4*4=16
5*1=5 5*2=10 5*3=15 5*4=20 5*5=25
6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36
7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49
8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64
9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81
break、continue
1、break在任何循环语句的主体部分,均可用break控制循环的流程。break用于强行退出循环,不执行循环中剩余的语句(break语句也在switch语句中使用)
2、continue用于循环语句中,用于终止某次循环过程,即跳过循环体中尚未执行的语句,接着下一次是否执行循环的判定
基础小结的练习题
代码样例:
package com.struct;
public class TestDomen {
public static void main(String[] args) {
//打印三角形 五行
for (int i = 0; i < 5; i++) {
for (int j = 5; j>=i; j--) {
System.out.print(" ");
}
for(int j = 0; j<=i; j++){
System.out.print("*");
}
for (int j = 1; j<=i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
输出结果:
*
***
*****
*******
*********