JAVA_Basis - 3. Method + Process Control + Cycle

1 method

A method in the Java language refers to a code block that encapsulates a specific logic function, makes the program structure clear, and facilitates code reuse.

1.1 Syntax:

Modifier returns the return value method name (parameter list) { method body } 1. The return value type needs to be used when the result is returned, and void is used when there is no return result. 2. The parameter handling method is flexible or optional 3. There is a return value required Write the return statement 4. The role of the return statement : return the result and end the current method





1.2 No return value method

Method name ();
method name (parameter value);

public void say(){
  System.out.println("Hello");
}
say();//调用
public void say(String str){
  System.out.println(str);
}
say("Hello");//调用
1.3 Methods with return values

Data type variable = method name ();
data type variable = method name (parameter value);

public int add(){
     int c=3+2;
     return c;
}
int d=add();//调用
public int add(int a,int b){
     int c=a+b;
     return c;
}
int d=add(5,4);//调用

Note: If there is a return value, return must be added and the value type returned by the return statement must match the return value type.

2 Process control

![Java language flow control includes control of branch results and control of loop structure.
[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-JXxF0CXS-1599406276332)(/img/bVbMgJd)]](https://img-blog.csdnimg.cn /20200906233156970.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzM4ODk1Nt,color=#,sizeFF_FF,center)

2.1 Branch structure

The branch structure can be regarded as tap water into the household: one bus (Main) + one /N branch (If/IF...ELSE/SWITCH...CASE), the water flow in the bus will be executed in order to reach the branch (IF... Statement) to determine whether branching (TRUE/FALSE) is needed, if water is needed (TRUE), water is supplied (into the cycle), and water is not needed (FALSE) to continue executing the code until the end. Questions that need to be judged and then selected should use branch structures.

2.1.1 IF single branch

Structure diagram

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-UJkWqcq5-1599406276336)(/img/bVbMuss)]

Case
int num=5;
  if(num%2==0){
     System.out.println(num+"是偶数");
} 

2.1.2 IF…ELSE multi-branch

The IF...ELSE statement is similar to the IF statement, both of which take two routes. The difference between them is that the IF...ELSE statement also processes another type of statement.

Structure diagram

[External link image transfer failed, the source site may have an anti-leech link mechanism, it is recommended to save the image and upload it directly (img-ipuQPlEc-1599406276339)(/img/bVbMusC)]

form
if( 条件表达式 ){
    ...
}else{
    ...
}
Case

Leap year

package com.mtingcat.javabasis.branchstructure03;

import java.util.Scanner;

/**
 *分支结构金典案例:平年闰年
 *	分支条件:
 *		1.能被4整除,并且不能被100整除
 *		2.能被400整除
 * @author MTing
 *
 */
public class branchStructureIf {
	public static void main(String[] args) {
		System.out.println("年号:");
		@SuppressWarnings("resource")
		Scanner scanner = new Scanner(System.in);
		int Y = scanner.nextInt();
		if(Y%4==0&&Y%100!=0||Y%400==0){
			System.out.println(Y + "年是闰年");
		}
		else{
			System.out.println(Y + "年是平年");
		}
	}
	

}

2.1.3 IF…ELSE IF nested branch

Structure diagram

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-yO7eoDRQ-1599406276343)(/img/bVbMuv1)]

form
if( 条件表达式 ){
    ...
}else if( 条件表达式 ){
    ...
}else{
    ...
}
Case
package com.mtingcat.javabasis.branchstructure03;

import java.util.Scanner;

/**
 * 商品打折
 * 	规则:满10000打7折,满20000打6折,满30000打5折
 * @author MTing
 *
 */
public class branchStructureIf02_discount {
	
	public static void main(String[] args) {
		System.out.println("消费总额:");
		@SuppressWarnings("resource")
		double price = new Scanner(System.in).nextDouble();
		double now = Discount(price);
		System.out.println(now);
	}
	
	public static double Discount(double price){
		if ( price >= 10000 ){
			price = price * 0.7;
		}else if ( price >=20000 ){
			price = price * 0.6;
		}else if ( price > 30000){
			price = price * 0.5;
		}
		return price;
	}
}


package com.mtingcat.javabasis.branchstructure03;

import java.util.Scanner;

/**
 * 按照学生的成绩给学生分等级
 * 	规则:100<= score >=90 优秀
 * 		80<= score < 90 良好
 * 		60<= score < 80 一般
 * 		0<= score <60 不及格
 * @author MTing
 *
 */
public class branchStructureIf03_studentScore {
	
	public static void main(String[] args) {
		System.out.println("请输入您的成绩");
		@SuppressWarnings("resource")
		double score = new Scanner(System.in).nextDouble();
		if( score <= 100 && score >= 90 ){
			System.out.println("您的成绩属于优秀");
		}else if( score >= 80 && score < 90 ){
			System.out.println("您的成绩属于良好");
		}else if( score >= 60 && score < 80 ){
			System.out.println("您的成绩属于一般");
		}else if( score >= 0 && score < 60 ){
			System.out.println("您的成绩属于不及格");
		}else{
			System.out.println("成绩无效,请重新输入");
		}
	}

}

2.1.4 SWITCh CASE statement

When a case is established, from this case backward through all cases, including default, until the end of the program or encounter the break program.

Structure diagram

[External link image transfer failed, the source site may have an anti-leech link mechanism, it is recommended to save the image and upload it directly (img-qSswNkHk-1599406276345)(/img/bVbMuAP)]

form
switch (key) {
		case value:
			break;
		default:
			break;
		}
Case
package com.mtingcat.javabasis.branchstructure03;

import java.util.Scanner;

/**
 * 数字匹配
 * @author MTing
 *
 */
public class branchStructureSwitch_dataMarry {
	public static void main(String[] args) {
		System.out.println("请输入您的数字");
		@SuppressWarnings("resource")
		int data = new Scanner(System.in).nextInt();
		switch (data) {
		case 1:
			System.out.println("匹配1");
			break;
		case 2:
			System.out.println("匹配2");
			break;
		case 3:
			System.out.println("匹配3");
			break;

		default:
			System.out.println("匹配错误");
			break;
		}
	}

}

2.2 Loop structure

Loop refers to the program code of a certain function that needs to be executed repeatedly in the program. It is judged by conditions whether to exit the loop. According to the conditions, it can also be divided into a structure that judges first, then loops, and loops first.

2.2.1 FOR Single Loop

Structure diagram

[External link image transfer failed, the source site may have an anti-leech link mechanism, it is recommended to save the image and upload it directly (img-YAqmSx0o-1599406276350)(/img/bVbMuEk)]

form
for (int i = 0; i < args.length; i++) {
	...		
}
Case
package com.mtingcat.javabasis.branchstructure03;
/**
 * 输出在1-1000中5的倍数
 * @author MTing
 *
 */
public class branchStructureFor01_outPutData {
	public static void main(String[] args) {
		for (int i = 0; i < 1000; i++) {
			if(i % 5 == 0){
				System.out.println(i);
			}	
		}
	}

}

2.2.2 FOR nested loop

Structure diagram

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-xdhxvR8g-1599406276353)(/img/bVbMuHW)]

form
for (int i = 0; i < args.length; i++) {
			for (int j = 0; j < args.length; j++) {
			    ...	
			}
		}	
Case
package com.mtingcat.javabasis.branchstructure03;
/**
 * 九九乘法表
 * @author MTing
 *
 */
public class branchStructureFor02_multiplicationTable {
	public static void main(String[] args) {
		System.out.println("九九乘法表啊");
		for (int i = 1; i < 10; i++) {
			for (int j = 1; j <= i; j++) {
				System.out.print(i +"*"+ j +"="+ i*j+"\t");
				
			}
			System.out.println("\n");
		}	
		
	}

}

2.2.3 CONTINUE 和 BREAK

form
for (int i = 0; i < args.length; i++) {
	if(判断条件){
        ...
        break;//如果成立,直接跳出这个for循环
    }	
    if(判断条件){
        ...
        continue;//如果成立,跳出本次for循环,进入下一轮
    }	
}
Case
package com.mtingcat.javabasis.branchstructure03;

import java.util.Scanner;

public class branchStructureFor03_continueBreak {
	public static void main(String[] args) {
		System.out.println("Your number:");
		@SuppressWarnings("resource")
		int j = new Scanner(System.in).nextInt();
		for (int i = 10; i > 0; i--) {
			if (j > i) {
				System.out.println("break");
				break;
			}
			if (j < i) {
				System.out.println("continue");
				continue;
			}
		}

	}

}

2.2.4 WHILE loop

Cycle after judgement

Structure diagram

[External link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-BTVmc82T-1599406276356)(/img/bVbMuMR)]

form
while (en.hasMoreElements()) {
			type type = (type) en.nextElement();
		}
Case
package com.mtingcat.javabasis.branchstructure03;

import java.util.Random;
import java.util.Scanner;

/**
 * 猜数字
 * @author MTing
 *
 */

public class branchStructureFor03_guessData {
	public static void main(String[] args) {
		System.out.println("猜1-6的随机数字");
		int Data = new Random().nextInt(10)+1;
		while (true) {
			@SuppressWarnings("resource")
			int Input = new Scanner(System.in).nextInt();
			if(Input > Data){
				System.out.println("大了呦");
			}else if(Input == Data){
				System.out.println("正确");
			}else{
				System.out.println("小了小了");
			}
			System.out.println("正确答案:" +Data);
		}
	
	}

}

2.2.3 DO...WHILE loop

Cycle first and judge later

form
 do {
			
		} while (condition);
Case
package com.mtingcat.javabasis.branchstructure03;

import java.util.Random;
import java.util.Scanner;

/**
 * 猜数字
 * @author MTing
 *
 */

public class branchStructureFor03_guessData {
	public static void main(String[] args) {
		System.out.println("猜1-6的随机数字");
		int Data = new Random().nextInt(10)+1;
		 do {
			 @SuppressWarnings("resource")
			int Input = new Scanner(System.in).nextInt();
				if(Input > Data){
					System.out.println("大了呦");
				}else if(Input == Data){
					System.out.println("正确");
				}else{
					System.out.println("小了小了");
				}
				System.out.println("正确答案:" +Data);
		} while (true);
	
	}

}

Guess you like

Origin blog.csdn.net/weixin_43388956/article/details/108438985