1. 程式人生 > >函式小練習

函式小練習

三個數比較最大值

public static void main(String[] args) {
	
	//設定鍵盤錄入
	Scanner sc=new Scanner(System.in);
	
	System.out.println("請輸入第1個數字:");
	int a=sc.nextInt();
	System.out.println("請輸入第2個數字:");
	int b=sc.nextInt();
	System.out.println("請輸入第3個數字:");
	int c=sc.nextInt();
	
	//設定變數max(這個變數名也可以改成別的,作用域不同,不受影響),來接受max方法的返回值
	int max=max(a,b,c);
	System.out.println(max);
	
}

public static int max(int a,int b,int c){
	
	//如果a>b且a>c,返回值是a
	if(a>b&&a>c){
		return a;
	//如果b>a且b>c,返回值是b
	}else if(b>a&&b>c){
		return b;
	//剩下的情況都返回c
	}else{
		return c;
	}
	
}

比較是否相等

public static boolean max(int a,int b) {
	/*
	 * 第一種,方法中的返回值寫int,第二種,返回值寫boolean
	 * int c =1; 
	 * int d=0; 
	 * if(a==b){
	 * 		 return c; }else{
	 *   return d; }
	 */

	if (a == b) {

		return true;
	} else {

		return false;

	}