JAVA基础3-流程控制

}else if(age<40){

System.out.println(“壮年时期”);

}else if(age<60){

System.out.println(“中年时期”);

}else{

System.out.println(“老年时期”);

}

}

}

//壮年时期

  1. switch-case

  2. 语法

switch(表达式){

case 常量1:

语句1;

[break;]

case 常量2:

语句2;

[break;]

default:

语句;

[break;]

}

  1. 示例

class Test7{

public static void main (String[] args){

int num=2;

switch(num){

case 0:

System.out.println(“zero”);

case 1:

System.out.println(“one”);

case 2:

System.out.println(“two”);

case 3:

System.out.println(“three”);

}

}

}

//two

//three

class Test7{

public static void main (String[] args){

int num=2;

switch(num){

case 0:

System.out.println(“zero”);

break;

case 1:

System.out.println(“one”);

break;

case 2:

System.out.println(“two”);

break;

case 3:

System.out.println(“three”);

break;

}

}

}

//two

  1. 注意点
  • switch在判定成功后,会继续执行剩下的代码,除非遇到break或代码执行完毕才会停止

  • switch中表达式只能是:byte short char int 枚举类型 String类型

  • case 之后只能声明常量

循环结构


根据循环结构,重复执行某段代码

  1. for循环
  • 语法

for(初始化,循环条件,迭代){

循环体

}

  • 示例

class forTest{

public static void main (String[] arges){

for(int i=0;i<4;i++){

System.out.println(“hello word”);

}

}

}

//hello word

//hello word

//hello word

//hello word

  1. while循环
  • 语法

初始化;

while(循环条件){

循环体;

迭代;

}

  • 示例

class whileTest{

public static void main (String[] agres){

int sum=0;

int i=0;

while(i<=100){

if(i % 2 == 0){

sum +=i;

}

i++;

}

System.out.println(sum);

}

}

//2550

  1. do-while循环
  • 语法

初始化

do{

循环体;

循环条件;

}while(迭代)

//也就是do-while至少执行一次

  • 示例

class doWhileTest{

public static void main (String[] args){

int sum=0;

int i=0;

do{

if(i % 2 ==0){

sum+=i;

}

i ++;

}while(i<= 100);

System.out.println(sum);

}

}

//2550

  1. 循环4个组成部分
  • 初始化部分

  • 循环条件部分

  • 循环体部分

  • 迭代部分

  1. 示例:做一个统计输入的正负数个数

import java.util.Scanner;

//引入模块

class Test1{

public static void main (String[] aegs){

Scanner scan =new Scanner(System.in);

//实例化

int positiveNumber = 0;

int negativeNumber = 0;

while(true){

int number =scan.nextInt();

if(number > 0){

positiveNumber ++;

}else if(number <0){

negativeNumber ++;

}else{

break;

//跳出循环

}

}

System.out.println(positiveNumber);

//输出统计正数出现个数

System.out.println(negativeNumber);

//输出统计负数出现个数

}

}

  1. 跳出循环
  • 在循环条件返回false

  • 循环体中执行break

  1. 不在循环条件部分限制次数结构
  • for( ; ; )

  • while(true)

  1. break和continue

| 关键字 | 使用范围 | 含义 |

| :-: | :-: | :-: |

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值