函数
定义:函数就是在类中具有特点功能的一顿独立小程序。也称为方法。
格式:
修饰符 返回值类型 函数名(参数类型 形式参数1,参数类型 形式参数2,…){
执行语句;
return 返回值;
}
返回值类型:函数运行后的结果的数据类型。
参数类型:是形式参数的数据类型。
形式参数:是一个变量,用于存储调用函数时传递给函数的实际参数。
实际参数:传递给形式参数的具体数值。
return : 用于结束函数。
返回值:该函数运算后的结果,该结果会返回给调用者。
特点:
1.将功能封装,便于对功能进行复用。
2.只有函数被调用才会执行。
3.对于函数没有具体返回值的时,返回值类型用关键字void表示。那么该函数中的 return语句可以省略不写。
注意:
1.函数中只能调用函数,不可以在函数内部定义函数。
2.定义函数时,函数的结果应该返回给调用者,交由调用者处理。
3.函数只为实现它所需功能,不要实现不需要的功能。
4.输出语句只能对有返回值类型的函数调用后打印,不能对没有返回值类型的函数 打印。
5.不要将代码都放在main函数里。
应用:
两个明确:
明确要定义的功能最后的结果是什么?明确返回值类型
明确在定义该功能的过程中,是否需要未知内容参与运算。明确参数列表
函数的重载
概念:在同一个类中,允许存在一个以上的同名函数,只要他们的参数个数和参数类型
不同即可。
特点:与返回值类型无关,只看参数列表:参数个数和参数类型。
好处:方便阅读,优化了程序设计。
函数练习
/*
函数练习
*/
class HanShuTest {
public static void main(String[] args) {
juXing(2,3);
System.out.println("————————————————");
getMax(34,6,45);
System.out.println("————————————————");
System.out.println(Max(7,3,5));
System.out.println("————————————————");
ifLiu(60);
System.out.println("————————————————");
chengFaBiao();
System.out.println("————————————————");
chengFaBiao(5);
}
/*
1,for的嵌套循环打印矩形用函数封装起来,根据所传参数打印行和列
*/
public static void juXing(int a,int b){
for (int x = 1; x <= a;x++ ){
for (int y = 1; y <= b;y++ ){
System.out.print("0");
}
System.out.println();
}
}
/*
定义一个功能获取三个整数中的最大数
*/
public static void getMax(int a,int b,int c){
if (a > b){
if (a > c){
System.out.println(a);
}else if (b > c){
System.out.println(b);
}else if (c > a){
System.out.println(c);
}else{
System.out.println("相等");
}
}
}
public static int Max(int a,int b,int c){
int tmop = (a > b) ? a : b;
return tmop = (tmop > c) ? tmop : c;
}
/*
定义一个方法求一个数的十六进制表现形式
*/
public static void ifLiu(int x){
while (x != 0){
int nun = x & 15;
if (nun > 9){
System.out.println((char)(nun - 10 + 'a'));
}else {
System.out.println(x);
}
x = x >>> 4;
}
}
/*
打印99乘法表的重载方法
*/
public static void chengFaBiao(){
for (int x = 1; x <= 9;x++ ){
for (int y = 1; y <= x;y++ ){
System.out.print(y+"x"+x+"="+x*y+'\t');
}
System.out.println();
}
}
public static void chengFaBiao(int num){
for (int x = 1; x <= num;x++ ){
for (int y = 1; y <= x;y++ ){
System.out.print(y+"x"+x+"="+x*y+'\t');
}
System.out.println();
}
}
}