day04-方法的定义练习&方法注意事项

This commit is contained in:
2025-12-25 12:00:14 +08:00
parent 6cd0a4a2bc
commit 79f1a412f7
2 changed files with 70 additions and 0 deletions

View File

@@ -32,6 +32,8 @@ package com.inmind;
案例定义方法实现2个整数值的相加之和并返回 案例定义方法实现2个整数值的相加之和并返回
*/ */
public class Demo01_method { public class Demo01_method {
public static void main(String[] args) { public static void main(String[] args) {
@@ -39,6 +41,35 @@ public class Demo01_method {
int sum = addMethod(10, 20); int sum = addMethod(10, 20);
System.out.println(sum); System.out.println(sum);
} }
//方法练习1_比较两个整数是否相同
public static boolean isEqual(int a,int b){
/*if (a == b) {
return true;
}else {
return false;
}*/
// return a==b?true:false;
return a==b;
}
//方法练习2_运算1到n的累和
public static int getSum(int n){
if (n < 1) {
System.out.println("您传递的参数不合法");
return -1;
}
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
return sum;
}
//方法练习3_打印n遍HelloWorld
public static void printHW(int n){
for (int i = 0; i < n; i++) {
System.out.println("helloworld");
}
}
//2个整数值的相加之和并返回 //2个整数值的相加之和并返回

View File

@@ -0,0 +1,39 @@
package com.inmind;
/*
学习方法的注意事项
1.方法要定义在类中方法外
2.当方法的返回值类型为void的时候需要写return不需要。
可以写return可以,但是return之后不能跟任何数据只能写return;
3.return:结束方法,跟是否返回方法的调用处无关,只要方法结束了一定返回方法调用处
4.在一个方法中可以写多个return吗
可以但是只能有一个return被调用
*/
public class Demo02_method_notification {
public static void main(String[] args) {
if (5 > 3) {
System.out.println("1");
return;
}
if (2 > 3) {
System.out.println("2");
return;
}
if (4 > 3) {
System.out.println("3");
return;
}
printHW(5);
System.out.println("程序结束");
}
//方法练习3_打印n遍HelloWorld
public static void printHW(int n){
for (int i = 0; i < n; i++) {
System.out.println("helloworld");
}
}
}