JAVA今日2021.8.12
阿新 • • 發佈:2021-08-12
JAVA 方法
格式
修飾符 返回值型別 方法名(引數型別,引數名){
...
方法體
...
return 返回值;//如果返回值型別為void,可以不用返回
}
形式引數:用於定義
實際引數:實際呼叫的
方法體:包含具體語句,定義該方法的功能
當方法返回一個值的時候;方法通常會被當作一個值,例:
int larger = max(10,20);
如果方法返回值是void,方法呼叫的一定是語句,例:
System.out.println("Hello,World!");
mt02
package JAVASE.method; public class mt02 { public static void main(String[] args) { int m = m(1, 2); System.out.println(m); } //比大小 public static int m(int a,int b){ int r = 0;//初始化 if (a==b){ System.out.println("a==b"); return 0;//終止方法 } if (a>b){ r=a; }else { r=b; } return r; } }
mtt00
package JAVASE.method; import java.util.Scanner; public class mtt00 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int x = 0; int y = 0; System.out.println("請輸入x:"); if (scanner.hasNextInt()){ x = scanner.nextInt(); } System.out.println("請輸入y:"); if (scanner.hasNextInt()){ y = scanner.nextInt(); } int xn = xn(x, y); System.out.println("較小的值為:"+xn); scanner.close(); } public static int xn(int a,int b){ int s=0; if (a==b){ System.out.println("a=b"); return 0; } if (a<b){ s=a; }else { s=b; } return s; } }
2021.8.12