public static void main(String[] arg0) {
System.out.println(「Hello」);
}複製代碼
方法的概念
方法用於包裹一段代碼,若是須要執行這段代碼能夠直接調用這個方法。
方法的定義與調用
定義帶有返回值的方法,調用方法獲取m的n次方的結果,並輸出:
public static void main(String[] arg0) {
int[] ary = {10, 20, 30};
modifyAry(ary);
System.out.println(Arrays.toString(ary));
}
public static void modifyAry(int[] ary){
ary[0] = 666;
}
public static void main(String[] arg0) {
int[] ary = {10, 20, 30};
modifyAry(ary);
System.out.println(Arrays.toString(ary));
}
public static void modifyAry(int[] ary){
ary = new int[]{666, 20, 30};
}複製代碼
做業
編寫一個方法getCM(int m, int n),接受m,n兩個整數參數,求其最小公倍數並返回。
main方法中在控制檯輸入m與n,而後調用該方法得到最小公倍數並輸出。
public class Homework1 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("請輸入m:");
int m = console.nextInt();
System.out.println("請輸入n:");
int n = console.nextInt();
int result = getCM(m, n);
System.out.println("最小公倍數是:"+result);
}
public static int getCM(int m, int n){
請實現方法
}
}複製代碼
2.18位身份證驗證算法,18位身份證號的最後一位是經過前17位計算得出,算法以下:
-
把身份證號前17位的每一位分別乘以不一樣的係數,前17位中每一位數字對應的係數以下:7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2
-
把每一位數字與係數的乘積結果相加求和。
-
把上一步的結果除以11,餘數只多是0,1,2,3,4,5,6,7,8,9,10這11個數字。
-
這11個數字分別對應的最後一位字符是: 1 0 X 9 8 7 6 5 4 3 2 (若是餘數爲2,則身份證最後一位字符則爲X)
要求:編寫一個方法verifyID(String id),接收一個18位身份證號字符串,通過運算後返回true(該身份證號合法)或者false(身份證號不合法)。
public class Homework2 {
public static void main(String[] args) {
String code = "37132319920531721X";
boolean ok = verifyID(code);
if(ok){
System.out.println("身份證號合法");
}else{
System.out.println("身份證號不合法");
}
}
public static boolean verifyID(String id){
請實現方法
}
}複製代碼
能夠將答案代碼,寫入留言區,代碼要不斷的編寫纔會培養「碼感」的呦!你不關注一下嗎?