从键盘任意输入n个实数,分别计算并输出其中正数的平均值和负数的平均值,需要考虑可能出现的异常,并给出异常处理

异常一共也就几种,数组越界,分母为0异常

 

 

第一种交给jvm处理

package chuki;

import java.util.*;

public class Two {
	public static void main(String[] args) {
		Scanner cin = new Scanner(System.in);
		int n = cin.nextInt();
		int t = 0, p = 0, sum1 = 0, sum2 = 0;
		for (int i = 1; i <= n; i++) {
			int x = cin.nextInt();
			if (x >= 0) {
				t++;
				sum1 += x;
			} else {
				p++;
				sum2 += x;
			}
		}
		double avg1 = sum1 * 1.0 / t;
		double avg2 = sum2 * 1.0 / p;
		System.out.println(avg1);
		System.out.println(avg2);
	}

}

第二种

package chuki;

import java.util.*;

public class Two {
	public static void main(String[] args) {
		Scanner cin = new Scanner(System.in);
		int n = cin.nextInt();
		int t = 0, p = 0, sum1 = 0, sum2 = 0;
		try{
			for (int i = 1; i <= n; i++) {
			int x = cin.nextInt();
			if (x >= 0) {
				t++;
				sum1 += x;
			} else {
				p++;
				sum2 += x;
			}
		}
		}catch(ArrayIndexOutOfBoundsException|NullPointerException e) {
			System.out.println("异常");
		}
		double avg1 = sum1 * 1.0 / t;
		double avg2 = sum2 * 1.0 / p;
		System.out.println(avg1);
		System.out.println(avg2);
	}

}

第三种按照上一个博客的格式就可以

你可能感兴趣的:(JAVA)