需求说明:
定义两个方法,在控制台输入一个数字,这两个方法可以求出1到该数字之间所有偶数之和、奇数之和,并将对应结果和返回。在main方法中调用该方法,并在控制台打印出结果。(有参数有返回值方法)
运行效果如图所示:
实现思路:
import java.util.Scanner; import javax.xml.soap.Text; public class EvenOdd { public static int even(int num,int sum) { System.out.print("1-"+num+"范围之间的偶数有:"); for (int i = 1; i <= num; i++) { if (i%2==0) { System.out.print(i+","); sum += i; } } return sum; } public static int odd(int num,int sum) { System.out.print("1-"+num+"范围之间的奇数有:"); for (int i = 1; i <= num; i++) { if (i%2!=0) { System.out.print(i+","); sum += i; } } return sum; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入一个数字:"); int num = sc.nextInt(); int sum = 0; int sumE1 = even(num,sum); int sumE2 = sumE1;//使用引用类型传递 System.out.println("偶数和为:"+sumE1); int sumO1 = odd(num, sum); int sumO2 = sumO1;//使用引用类型传递 System.out.println("奇数和为:"+sumO1); } }