`

java写从键盘输入十个数并计算结果

    博客分类:
  • J2SE
阅读更多
import java.io.*;

public class SortCount {

static InputStreamReader in;
static BufferedReader reader;
static {
	in = new InputStreamReader(System.in);
	reader = new BufferedReader(in);
}

// 读取整数
public static int readInt() {
  int i = 0;
  try {
    String s1 = reader.readLine();
    i = Integer.parseInt(s1);
  } catch (Exception e) {
	System.exit( 0 );
  }
  return i;
}

// 冒泡排序
public static void sort(int[] num) {
	int mid;
	int i, j;
	for (i = 0; i < 10; i++)
		for (j = i + 1; j < 10; j++)
			if (num[i] > num[j]) {
				mid = num[i];
				num[i] = num[j];
				num[j] = mid;
			}
}

// 正数求和
public static int total(int[] num) {		
	int result = 0;
	for (int i = 0; i < num.length; i++) {
		if (num[i]>0)
			result = result + num[i];
	}
	return result;
}

public static void main(String args[]) {
	int a[] = new int[10];
	for (int i = 0; i < 10; i++) {
		System.out.println("请输入第" + (i + 1) + "个数:");
		a[i] = SortCount.readInt();
	}
	
	// 排序
	sort(a);
	
	// 求和
	int result = total(a);
	System.out.println(result);
}
}

 

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics