- 所谓的函数就是实现的集体方法(函数=方法);
- 函数可以有返回值(int char ······),也可以没有(void),要用reture来返回;
- 为什么要使用函数呢?是使代码的复用性提高,以及代码简单化。
我们来用函数来实现两个数比较大小:
1.有返回值 int类型
package com.ccy.demo;
public class Dome13 {
public static void main(String[] args) {
// 定义两个整型变量
int a = 10;
int b= 19;
// 调用ComNumber函数
int result = ComNumber(a ,b);
System.out.println(result+"大");
int d = 90;
int f = 5858;
int result1 = ComNumber(d,f);
System.out.println( result1+"大");
}
// 定义一个ComNumber的函数 返回值是int类型
public static int ComNumber(int a, int b){
// 定义返回值
int c = 0 ;
// 具体的方法
if (a>b){
c = a;
}else
{
c = b ;
}
return c; //返回值
}
}
2.没有返回值void
package com.ccy.demo;
public class Dome13 {
public static void main(String[] args) {
// 定义两个整型变量
int a = 10;
int b= 19;
//调用ComNumber 也不需要去接受ComNumber
ComNumber(a,b);
}
// 定义一个ComNumber的函数 返回值是void类型就不需要返回return
public static void ComNumber(int a, int b){
// 具体的方法
if (a>b){
System.out.println(a+"大");
}else
{
System.out.println(b+"大");
}
}
}
3.返回值为void,有return时,程序结束
package com.ccy.demo;
public class Dome13 {
public static void main(String[] args) {
// 定义两个整型变量
int a = 90;
int b= 19;
//调用ComNumber 也不需要去接受ComNumber
ComNumber(a,b);
}
// 定义一个ComNumber的函数 返回值是void类型就不需要返回return
public static void ComNumber(int a, int b){
// 具体的方法
if (a <0 || b<0)
{
return;
}
if (a>b){
System.out.println(a+"大");
}else
{
System.out.println(b+"大");
}
}
}