JAVA PAT (Basic Level) Practice 1054 求平均值

JAVA PAT (Basic Level) Practice 1054 求平均值_第1张图片
实现代码

import java.util.Arrays;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int count = Integer.parseInt(scanner.nextLine());
    String line = scanner.nextLine();
    String[] strs = line.split(" ");
    strs = Arrays.copyOf(strs, count);
    double sum = 0;
    int avl = 0;
    for (String str : strs) {
      double val = 0;
      boolean isNum = true;
      try {
        val = Double.parseDouble(str);
      } catch (Exception e) {
        isNum = false;
      }
      if (isNum) {
        if (val <= 1000 && val >= -1000) {
          String n = String.valueOf(val);
          if (n.substring(n.indexOf(".") + 1).length() <= 2) {
            avl++;
            sum += val;
            continue;
          }
        }
      }
      System.out.println("ERROR: " + str + " is not a legal number");
    }
    System.out.println("The average of " + avl + " numbers is " + (avl == 0 ? "Undefined" : String.format("%.2f", sum / avl)));
  }
}

你可能感兴趣的:(java,PAT)