5方法定义及调用

5方法定义及调用

课堂作业

1、无参方法

编写一个无参方法,输出Hello。

public static void main(String[] args) {

System.out.println("hello world");

}

2int型参数方法

编写一个得到两个int型参数方法,返回两个参数的和。

public class two {

// 编写一个得到两个int型参数方法,输出两个参数的和。

// 定义两个int参数,在定义一个C统计和

int a=2;

int b=3;

int c=a+b;

//编写一个sum方法用于打印c的值

public void sum() {

System.out.println(c);

}

}

public class twoT {

public static void main(String[] args) {

// 实例化:为一个对象开一个新的空间让它住下来

// 实例化TWO让它在twot保存下来

two T=new two();

// 调用two中的sum方法

T.sum();

}

}

3、调用

编写一个无参方法,输出欢迎语句,调用该方法。

public class Three {

//编写一个无参方法,输出欢迎语句,调用该方法。

public void ShuChu() {

System.out.println("hello yanhui");

}

}

public class ThreeT {

public static void main(String[] args) {

Three T=new Three();

T.ShuChu();

}

}

4、调用

编写一个得到两个int型参数方法,输出两个参数的和;在主函数

中产生两个随机整数作为该方法的参数,调用该方法,输出结果。

public class four {

public void shuchu() {

Random x=new Random();

int a=x.nextInt(100);

int b=x.nextInt(50);

int c=a+b;

System.out.println("c="+c);

}

}

public class fourT {

public static void main(String[] args) {

four F=new four();

F.shuchu();

}

}

课后作业:

1、求整数n的阶乘

编写一个方法,求整数n的阶乘,例如5的阶乘是1*2*3*4*5。 [必

做题]

 package five方法定义调用;

import java.util.Scanner;

public class jiecheng {
    // 编写一个方法,求整数n的阶乘,例如5的阶乘是1*2*3*4*5。
    public static void main(String[] args) {
        
        int sum = 1;
        Scanner x1 = new Scanner(System.in);
        System.out.println("请输入一个整数:");
        int x = x1.nextInt();
        for (int i = 1; i <= x; i++) {
            sum = sum * i;
        }
        System.out.println(x + "的阶乘为:" + sum);

    }

}

2、平年还是闰年

编写一个方法,判断该年份是平年还是闰年。[必做题]

 package five方法定义调用;

import java.util.Scanner;

public class pingnianrunnian {
//    编写一个方法,判断该年份是平年还是闰年。[必做题]
    public static void main(String[] args) {
        System.out.println("请输入年份:");
        Scanner x1=new Scanner(System.in);
        int year=x1.nextInt();
        
        if (year %4==0 && year%100==0||year%400==0) {
            System.out.println("平年");
        }else {
            System.out.println("闰年");
        }
        
    }
}

选做题:

1、大于200的最小的质数

编写一个方法,输出大于200的最小的质数。[选做题]

package five方法定义调用;

public class zhishu {
    public static void main(String[] args) {
//        for(int i=201;i<300;i++) {
//            if (i%2!=0 && i%3!=0 && i%5!=0&& i%7!=0 && i%9!=0) {
//                   System.out.println(i);
//
//                   break;
//            }
//        }
        int n=201,i;
        outer:
        for(;;n++){
        for(i=2;i*i<=n;i++) if(n%i==0)continue outer;
        break;
        }
        System.out.println(n);

    }
}

2、按从小到大的顺序输出

写一个方法,功能:定义一个一维的int 数组,长度任意,然后将

它们按从小到大的顺序输出(使用冒泡排序)(知识点:方法的定义

和访问)。[选做题]

 int temp;

        int[] arr = new int[] { 1, 6, 2, 3, 9, 4, 5, 7, 8 };

        Arrays.sort(arr);// java提供对数组排序

        for (int n : arr) {

            System.out.println(n);

        }

原文地址:https://www.cnblogs.com/liuyanhuiyanhui/p/12423744.html