例4.1 在主函数中调用其他函数
public class Demo4_1 {
public static void main(String[] args) {
printstar();
print_message();
printstar();
}
private static void print_message() {
System.out.println("Welcome to java!");
}
private static void printstar() {
//输出30个"*"
System.out.println("******************************");
}
}
例4.2 调用函数时的数据传递
import java.util.Scanner;
public class Demo4_2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a, b, c;
System.out.print("Please enter two integer nembers:");
a = sc.nextInt();
b = sc.nextInt();
c = max(a, b);
System.out.println("max="+c);
}
private static int max(int a, int b) {
int z;
z = a > b ? a : b;
return z;
}
}
例4.3 对被调用的函数做声明
import java.util.Scanner;
public class Demo4_3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
float a, b, c;
System.out.print("Please enter a, b:");
a = sc.nextFloat();
b = sc.nextFloat();
c = add(a, b);
System.out.println("sum = "+c);
}
private static float add(float a, float b) {
return (a+b);
}
}
例4.4 函数指定为内置函数
public class Demo4_4 {
public static void main(String[] args) {
int i = 10;
int j = 20;
int k = 30;
int m;
m = max(i, j, k);
System.out.println("max = "+m);
}
public static final int max (int a,int b,int c) {
if(b>a) {
a = b;
}
if(c>a) {
a = c;
}
return a;
}
}
例4.5 求3个数中最大的数(分别考虑整数、双精度数、长整数的情况)
import java.util.Scanner;
public class Demo4_5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i1, i2, i3, i;
i1 = sc.nextInt();
i2 = sc.nextInt();
i3 = sc.nextInt();
i = max(i1,i2,i3);
System.out.println("i_max = "+i);
double d1, d2, d3, d;
d1 = sc.nextDouble();
d2 = sc.nextDouble();
d3 = sc.nextDouble();
d = max(d1,d2,d3);
System.out.println("d_max = "+d);
long g1, g2, g3, g;
g1 = sc.nextLong();
g2 = sc.nextLong();
g3 = sc.nextLong();
g = max(g1,g2,g3);
System.out.println("g_max = "+g);
}
public static int max(int a, int b, int c){
if (b>a)
a=b;
if (c>a)
a=c;
return a;
}
public static double max (double a, double b, double c) {
if (b>a)
a=b;
if (c>a)
a=c;
return a;
}
public static long max(long a, long b, long c) {
if (b>a)
a=b;
if (c>a)
a=c;
return a;
}
}
原文:https://www.cnblogs.com/Gazikel/p/13562005.html