Files
javaSE-0419/day04/src/com/inmind/method01/Demo03.java

52 lines
1.4 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.inmind.method01;
/*
方法的三种调用方式:
1.直接调用 : 方法名(参数列表)
2.赋值调用:数据类型 变量名 = 方法名(参数列表)
3.打印输出调用: System.out.println(方法名(参数列表));
总结:直接调用可以调用任意方法,赋值和打印输出调用只能调用有返回值的方法。
*/
public class Demo03 {
public static void main(String[] args) {
//直接调用
print(10);
getSum(10);
//赋值调用
//void v = print(10); 无返回值的方法不能赋值给变量
int sum = getSum(10);//自动类型转换
//打印输出调用(将一个方法的返回值作为另一个方法的参数)
//System.out.println(print(10));无返回值的方法不能打印输出
System.out.println(getSum(10));
print(getSum(3));
}
//没有返回值的方法
public static void print(int n){
if (n < 1) {
return;//提前结束方法如果n小于1则直接返回不执行下面的代码
}
for (int i = 0; i < n; i++) {
System.out.println("helloworld");
}
}
//有返回值的方法
public static int getSum(int n){
int sum = 0;
for (int i = 1; i <= n; i++) {
// sum = sum + i;
sum += i;
}
return sum;
}
}