本题的基本要求非常简单:给定N个实数,计算它们的平均值。但复杂的是有些输入数据可能是非法的。一个“合法”的输入是[-1000,1000]区间内的实数,并且最多精确到小数点后2位。当你计算平均值的时候,不能把那些非法的数据算在内。
输入格式:
输入第一行给出正整数N(<=100)。随后一行给出N个实数,数字间以一个空格分隔。
输出格式:
对每个非法输入,在一行中输出“ERROR: X is not a legal number”,其中X是输入。最后在一行中输出结果:“The average of K numbers is Y”,其中K是合法输入的个数,Y是它们的平均值,精确到小数点后2位。如果平均值无法计算,则用“Undefined”替换Y。如果K为1,则输出“The average of 1 number is Y”。
输入样例1:
7 5 -3.2 aaa 9999 2.3.4 7.123 2.35
输出样例1:
ERROR: aaa is not a legal number ERROR: 9999 is not a legal number ERROR: 2.3.4 is not a legal number ERROR: 7.123 is not a legal number The average of 3 numbers is 1.38
输入样例2:
2 aaa -9999
输出样例2:
ERROR: aaa is not a legal number ERROR: -9999 is not a legal number The average of 0 numbers is Undefined
主要利用正则表达式来解决:
1 package com.hone.basical; 2 3 import java.text.DecimalFormat; 4 import java.util.Scanner; 5 import java.util.regex.Matcher; 6 import java.util.regex.Pattern; 7 8 /** 9 * 原题目:https://www.patest.cn/contests/pat-b-practise/1054 10 * @author Xia 11 * 注意:1、合法数字个数是0的时候The average of 0 numbers is Undefined 12 * 2、合法数字个数是1的时候 要输出The average of 1 number is Y 13 */ 14 15 public class basicalLevel1054average { 16 17 public static void main(String[] args) { 18 Scanner in = new Scanner(System.in); 19 int N = in.nextInt(); 20 21 double total = 0; 22 int totalNum = 0; 23 //整理思路利用正则表达式判断输入的是否是位于[-1000,1000]之间, 24 //最多精确到小数点后2位的数字 25 for (int i = 0; i < N; i++) { 26 String mayNum = in.next(); 27 if (isNum(mayNum)) { //如果是数字 28 double num =Double.parseDouble(mayNum); 29 if (num<=1000&&num>=-1000) { 30 total+=Double.parseDouble(mayNum); 31 totalNum++; 32 }else { 33 System.out.println("ERROR: "+mayNum +" is not a legal number"); 34 } 35 }else { 36 System.out.println("ERROR: "+mayNum +" is not a legal number"); 37 } 38 } 39 if (totalNum>1) { 40 DecimalFormat df =new DecimalFormat("##0.00"); 41 String sp = df.format(total/(double)totalNum); 42 System.out.println("The average of "+totalNum +" numbers is " 43 +sp); 44 }else if (totalNum == 1) { 45 System.out.printf("The average of %.0f number is %.2f ", totalNum, total / totalNum); 46 }else { 47 System.out.println("The average of 0 numbers is Undefined"); 48 } 49 50 } 51 52 //定义函数判断是否是合法的数字 53 public static boolean isNum(String str){ 54 String p = "((\-?)(\d+))(\.(\d){0,2})?"; 55 Pattern pattern = Pattern.compile(p); 56 Matcher isNum = pattern.matcher(str); 57 if (!isNum.matches()) { 58 return false; 59 } 60 return true; 61 } 62 63 }