小楼昨夜-听风雨
2021-05-24 10:40
采纳率: 100%
浏览 44

java异常问题求解

下面代码运行出来输入5和0.5出现错误求:用

try{

}catch(){

}finally{

}来解决答案

package edu.sdp.java.textbook;

import java.util.Scanner;

public class CalculatorTest {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		System.out.println("请输入第一个操作数(整数)");
		int oper1 = scan.nextInt();
		System.out.println("请输入第二个操作数(整数)");
		int oper2 = scan.nextInt();
		System.out.println("------四则运算结果-------");
		System.out.println(oper1+"+"+oper2+"="+Calculator.add(oper1, oper2));
		System.out.println(oper1+"-"+oper2+"="+Calculator.subract(oper1, oper2));
		System.out.println(oper1+"*"+oper2+"="+Calculator.multiply(oper1, oper2));
		System.out.println(oper1+"/"+oper2+"="+Calculator.divide(oper1, oper2));
	}

}









package edu.sdp.java.textbook;

import java.util.Scanner;

public class CalculatorTest2 {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		try{
		System.out.println("请输入第一个操作数(整数)");
		int oper1 = scan.nextInt();
		System.out.println("请输入第二个操作数(整数)");
		int oper2 = scan.nextInt();
		System.out.println("------四则运算结果-------");
		System.out.println(oper1+"+"+oper2+"="+Calculator.add(oper1, oper2));
		System.out.println(oper1+"-"+oper2+"="+Calculator.subract(oper1, oper2));
		System.out.println(oper1+"*"+oper2+"="+Calculator.multiply(oper1, oper2));
		System.out.println(oper1+"/"+oper2+"="+Calculator.divide(oper1, oper2));
		}catch(ArithmeticException ex){
			System.out.println("除数不能为0,请重新输入");
		}finally{
			scan.close();
		}
	}

}

错误问题

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

5条回答 默认 最新

相关推荐 更多相似问题