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

本文介绍了一个简单的Java程序,该程序通过冒泡排序算法对用户输入的10个整数进行排序,并计算所有正数之和。程序首先定义了一个用于从标准输入读取整数的方法,然后实现了冒泡排序算法,最后计算并输出了所有正数的总和。
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);
}
}

 

可以使用`Scanner`类从键盘获取用户输入的两个数,然后进行相除操作。以下是一个示例代码,该代码还对除数为负数和零的情况进行了异常处理: ```java import java.util.Scanner; class NegativeException extends Exception { String message; public NegativeException(int n) { message = "The divisor, " + n + ", could not be negative!"; } } class ZeroException extends Exception { String message; public ZeroException(int m) { message = "The divisor, " + m + ", could not be zero!"; } } class My { public My(int m, int n) throws Exception { if (n < 0) { throw new NegativeException(n); } else if (n == 0) { throw new ZeroException(n); } else { System.out.println("The result of division is: " + (float) m / n); } } } public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Please input the dividend: "); int dividend = in.nextInt(); System.out.println("Please input the divisor: "); int divisor = in.nextInt(); try { new My(dividend, divisor); } catch (NegativeException e) { System.out.println(e.message); } catch (ZeroException e) { System.out.println(e.message); } catch (Exception e) { System.out.println("An unexpected error occurred: " + e.getMessage()); } System.out.println("Program execution completed."); } } ``` 上述代码参考了引用[3]的异常处理和输入输出的逻辑,通过`Scanner`类获取用户输入的两个整数,创建`My`对象进行相除操作,对可能出现的异常进行捕获和处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值