欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java统计 m ~ n 中奇数偶数的个数

程序员文章站 2024-02-02 15:24:46
...
package practice;

import java.util.Scanner;

public class TargetM_to_N {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		System.out.print("请输入起点数:");
		if (sc.hasNextInt()) {
			int beginNum = sc.nextInt();
			System.out.print("请输入终点数:");
			if (sc.hasNextInt()) {
				int endNum = sc.nextInt();
				if (beginNum >= endNum) {
					System.out.println("\n提示:起点数必须小于终点数!");
				} else {
					if (beginNum > 0 && endNum > 0) {
						int sumEven = 0, sumOdd = 0;
						for (int i = beginNum; i <= endNum; i++) {
							if (i % 2 == 0) {
								System.out.println(i + "是偶数!");
								sumEven++;
							} else {
								System.out.println(i + "是奇数!");
								sumOdd++;
							}
						}
						System.out.println("\n提示:奇数共 " + sumEven + " 个,奇数共 " + sumOdd + " 个!");
					} else {
						System.out.println("\n提示:起点数和终点数必须同时大于零!");
					}
				}
			} else {
				System.out.println("\n提示:请输入整数!");
			}
		} else {
			System.out.println("\n提示:请输入整数!");
		}

		sc.close();

	}

}