32

Java基础篇(03):流程控制语句,和算法应用

 3 years ago
source link: http://mp.weixin.qq.com/s?__biz=MzU4Njg0MzYwNw%3D%3D&%3Bmid=2247484720&%3Bidx=1&%3Bsn=9900e43240326576b9024665293fec4b
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

一、分支语句

流程控制语句对任何一门编程语言都是非常重要的,Java中基于流程控制程序执行的不同步骤和代码块。

1、IF条件

IF条件语句会根据不同的判断条件执行不同的语句,if后括号内的条件是否成立关键步骤,IF条件的判断结果必然要是true或false。IF…Else语句则是满足IF条件,就执行相应代码块,否则就执行Elase代码块。

public class Process01 {
public static void main(String[] args) {
// 演示:Node01
if (compare01(40,30)){
System.out.println("40>30:true");
} else {
System.out.println("40>30:false");
}
// 演示:Node02
if (compare01(10,20) && compare01(20,30)){
System.out.println("条件成立");
} else {
System.out.println("条件不成立");
}
// 演示:Node03
if (compare01(20,10) || compare01(20,30)){
System.out.println("条件成立");
} else {
System.out.println("条件不成立");
}
// 演示:Node04
if(compare02(1,1))
if(compare02(2,2))
System.out.println("Running...");
// 演示:Node05
if(compare01(1,2))
if(compare01(5,3)){
System.out.println("5>3");
}
}

private static boolean compare01 (int num1,int num2){
System.out.println("判断:num1="+num1+";num2="+num2);
return num1 > num2 ;
}
private static boolean compare02 (int num1,int num2){
System.out.println("判断:num1="+num1+";num2="+num2);
return num1 == num2 ;
}
}

节点案例,测试结果描述:

  • Node01:如果if条件不成立,则执行else流程或者结束;

  • Node02:逻辑且判断,任何条件不成立,则直接结束;

  • Node03:逻辑或判断,任何条件成立,则直接进入分支;

  • Node04:IF的格式,可以去掉{},后续语句会作为分支;

  • Node05:IF语句面试题,不会输出任何内容,第二个语句作为分支;

注意:在流程控制语句中必须使用大括号,即使只有一行代码,避免采用单行的编码方式,这是基础规范。在上面的测试节点4和5,代码看着就感觉扎心。

2、IF-Else-IF条件

Else…IF分支语句用于多种情况进行的判断处理,直到分支判断条件成功,执行分支模块代码,如果没有else条件,可以所有分支都不满足,直接结束。

public class Process02 {
public static void main(String[] args) {
elseIf(11) ;
elseIf(9) ;
elseIf(5);
}

private static void elseIf (Integer num){
if (num > 10){
System.out.println("num > 10");
} else if (num > 7){
System.out.println("num > 7");
} else if (num > 4){
System.out.println("num > 4");
} else {
System.out.println("num < 4");
}
}
}

注意:根据条件逐个判断,直到找到第一个满足的条件,不会再继续往下面的判断执行,分支语句执行完毕就会退出当前的else…if流程。超过3层的的逻辑判断代码可以使用卫语句、策略模式、状态模式等来实现。

3、Switch条件

流程描述:switch语句先获取表达式的值,判断表达式的值与case语句后的常量值是否相同,匹配成功则执行该case后的代码块,直到遇到break语句后终止,如果缺失break打断,则继续匹配下一case常量,直到遇到break为止。如果条件全不匹配,则执行default后面的语句。default语句可选,如果不存在default语句,同一个switch语句,case的常量值必须互不相同。

public class Process03 {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("What day is it today:");
String value = scan.next();
weekInfo(value);
}

private static void weekInfo (String value){
switch (value) {
case "Monday":
System.out.println("Monday");
break;
case "Tuesday":
System.out.println("Tuesday");
break;
case "Wednesday":
System.out.println("Wednesday");
break;
case "Thursday":
System.out.println("Thursday");
break;
case "Friday":
System.out.println("Friday");
break;
case "Saturday":
System.out.println("Saturday");
break;
case "Sunday":
System.out.println("Sunday");
break;
default:
System.out.println("Matching failure");
break;
}
}
}

注意:从JDK1.7之后,switch支持对String字符串的匹配。

二、循环语句

循环语句就是在满足特定条件的情况下,反复执行同个操作。循环语句包括:for循环、while循环、do···while循环。

1、For循环

Java开发中最有用的循环方式,也是诸多算法中的基础控制语句,在常见的很多算法编码实现中,都需要借助for循环方式。

public class Process04 {
public static void main(String[] args) {
// Node01
int sum = 0;
for(int i=1; i<=100; i++) {
sum += i;
}
System.out.println(sum);

// Node02
String[] nameArr = {"Java","C++","C#"} ;
for (String name:nameArr){
System.out.println("name="+name);
}

// Node03
// 输出 i = 13
int i = 0;
for (i++; i++ < 10; i++);
System.out.println(++i);

// 输出:j=3 6 9
int j = 0;
for (j++; j++ < 10; j++){
System.out.println(++j);
}
}
}

节点案例,测试结果描述:

  • Node01:for循环作为计算中的常用方式;

  • Node02:foreach遍历模式,简化循环操作,也可以改写为for语句;

  • Node03:循环for语句的基础执行机制,两道面试常见题;

注意:越是基础的东西,学起来越难,for语句作为很多算法实现的基础控制,理解起来相当的绕。

2、While循环

while循环语句首先判断条件是否成立,成立才执行循环体;

do···while循环语句先执行一次循环体,然后判断条件是否成立,所以do···while至少会执行一次;

public class Process05 {
public static void main(String[] args) {
int num1 = 1;
int num2 = 1;

// while循环
while(num1 <= 3) {
System.out.println("num1 == " + num1);
num1++;
}

// do...while循环
do {
System.out.println("num2 == " + num2);
num2++;
} while(num2 <= 3);
}
}

注意:while循环在实际的开发中,因为极其容易导致死循环,所以使用并不多。

三、流程中断

Java中有三种流程中断语句,关键字分别为break、continue、return语句。

1、Return语句

Java中最常用的流程控制关键字,当执行return语句后,从该方法返回,返回到调用该方法的业务流程中。

public class Process06 {
public static void main(String[] args) {
System.out.println(getNum1());
System.out.println(getNum2());
}
public static int getNum1 (){
int a =100;
try{
return a+1; // 这里是运算逻辑,非赋值
}catch(Exception e){
e.printStackTrace();
}finally{
return a;
}
}
public static int getNum2 (){
int a =100;
try{
return a++; // a++ -> a=a+1 此时a的值改变
}catch(Exception e){
e.printStackTrace();
}finally{
return a;
}
}
}

return 常在位置

  • return语句只在方法最后出现一次。

  • return语句仅在try和catch里面都出现。

  • return语句仅在try和方法最后都出现。

  • return语句仅在catch和方法的最后都出现。

2、Break语句

break中断语句常用在for、while、do···while循环中,用于退出当前整个循环流程,非当前这一次循环。

public class Process07 {
public static void main(String[] args) {
for (int i = 1 ; i < 3 ; i++){
if (i == 2){
break ;
}
System.out.println("i = " + i);
}
}
}

3、Continue语句

Continue中断语句常用在for、while、do···while循环中,用于退出当前这一次循环,进入下一次循环。

public class Process08 {
public static void main(String[] args) {
for (int i = 1 ; i < 3 ; i++){
if (i == 1){
continue ;
}
System.out.println("i = " + i);
}
}
}

四、应用场景

1、冒泡排序算法

public class Process09 {
public static void main(String[] args) {
int[] score = {9,8,7,6,5} ;
// 排序次数:最多 length - 1 次
for (int i = 0 ; i < score.length -1 ; i ++){
// 当前排序的集合区间,排序完一个数据就放弃一个
for (int j = 0 ; j < score.length - i - 1 ; j++){
// 冒泡排序:把结果大的向后扔
if (score[j] > score[j+1]){
int temp = score[j] ;
score[j] = score[j+1] ;
score[j+1] = temp ;
}
}
}
// 输出排序后的结果集
for (int i = 0 ; i < score.length ; i++){
System.out.print(score[i]);
}
}
}

2、排列组合算法

有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?

public class Process10 {
public static void main(String[] args) {
arrange() ;
}
public static void arrange (){
int i=0; // 百位数
int j=0; // 十位数
int k=0; // 个位数
int t=0; // 计数器
for (i = 1 ; i <= 4 ; i++){
for (j = 1 ; j <= 4 ; j++){
for (k = 1 ; k <=4 ; k++){
if (i != j && j != k && k != i){
t += 1 ;
System.out.print(i*100+j*10+k+"--");
}
}
}
}
System.out.println();
System.out.println("t="+t);
}
}

3、递归常见算法

基于递归思想的各种计算方法实现。

public class Process11 {
public static void main(String[] args) {
System.out.println(getSumOne(100));
System.out.println(getSumTwo(30));
System.out.println(getSumThree(5));
}
/**
* 使用递归的方式计算1+2+...+100
*/

public static int getSumOne (int i){ // 传入100
int sum ;
if (i == 1){
return 1 ;
}
else {
sum = i + getSumOne(i - 1) ;
}
return sum ;
}
/**
* 一列数的规则如下: 1、1、2、3、5、8、13、21、34...
* 求第30位数是多少, 用递归算法实现
*/

public static int getSumTwo (int i){ // 传入第几位数下标
if (i <= 0){
return 0 ;
} else if (i == 1 || i == 2){ // 处理前面2位的1,1
return 1 ;
} else { // 当前位数是前两位之和
return getSumTwo(i - 1) + getSumTwo(i - 2) ;
}
}
/**
* 1*2*3*...*100 递归计算阶乘
*/

public static int getSumThree (int i){
if (i == 1){
return i ;
} else {
return i * getSumThree (i - 1) ;
}
}
}

五、源代码地址

GitHub·地址
https://github.com/cicadasmile/java-base-parent
GitEE·地址
https://gitee.com/cicadasmile/java-base-parent

MzYveqr.jpg!web


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK