排序,计算平均数。
package com.stx.exercise.p2;
import java.util.Scanner;
/**
* This program can do receive some numbers .it will sort the numbers and calculate the average.
* @param va will be save the sum.
* @param num is record the array length.
*/
public class Four_TanZheng1 {
int va;
int num;
/**
* the method will receive numbers and sort finally calculate the average
* */
void receiveGrade() {
Scanner input = new Scanner(System.in);
System.out.println("input your number split by comma:");
String str = input.nextLine();
String arrStr[] = str.split(",");
double arrInt[] = new double[arrStr.length];
for (int i = 0; i < arrStr.length; i++) {
double a = Integer.parseInt(arrStr[i]);
arrInt[i] = a;
}
/**
* the method is bubble sort .
* idea is using for loop the length and compare the value.
* meanwhile set the flag judge the all condition if the all element was sorted that will be over;
* */
boolean flag = true;
for (int i = 0; i < arrInt.length - 1; i++) {
for (int j = 0; j < arrInt.length - 1 - i; j++) {
if (arrInt[j] > arrInt[j + 1]) {
double temp = arrInt[j];
arrInt[j] = arrInt[j + 1];
arrInt[j + 1] = temp;
flag = false;
}
}
if (flag) {
break;
}
}
/*
* create the double type arrays copy before array that was watch the elements.
* other record the sum
* */
System.out.println("sorted arrays:");
double[] generativeGrade=arrInt;
for (double arr:generativeGrade){
System.out.println(arr);
}
System.out.println();
double[] aa=arrInt;
for (int i = 0; i < aa.length; i++) {
va+=aa[i];
}
System.out.println("you average is :"+va);
//record the times was calculate the average.
num=aa.length;
System.out.println(va/num);
}
public static void main(String[] args) {
Four_TanZheng1 tan = new Four_TanZheng1();
tan.receiveGrade();
}
}