关于异常捕获的问题 有大神能指点一下小菜鸟吗
import java.util.*;
abstract class RedEnvelope{
public double remainMoney; //红包当前金额
public int remainPeople; //当前参与抢红包的人数
public double money; //当前用户抢到的金额
public abstract double giveMoney(); //抽象方法,具体怎么抢由子类完成
}
class RandomRedEnvelope extends RedEnvelope{
double minMoney;
int integerRemainMoney;
int randomMoney;
Random random; //为什么这句不能直接写进try里面
RandomRedEnvelope(double remainMoney,int remainPeople){
random = new Random();
minMoney = 0.01;
this.remainMoney = remainMoney;
this.remainPeople = remainPeople;
integerRemainMoney = (int)(remainMoney*100); //此时整型的剩余金额单位已是"分"
if(integerRemainMoney<remainPeople*(int)(minMoney*100)){
throw new java.io.IOException("你输入的金额过少,请确保每人至少能分到1分钱");
}
}
public double giveMoney(){
if(remainPeople <= 0){
return 0;
}
if(remainPeople == 1){
money = remainMoney;
remainPeople--;
return money;
}
randomMoney = random.nextInt(integerRemainMoney); //金额区间为[0,519)
if(randomMoney<(int)(minMoney*100)){
randomMoney = (int)(minMoney*100);
}
int leftOtherPeopleMoney = integerRemainMoney - randomMoney;
int otherPeopleNeedMoney = (remainPeople-1)*(int)(minMoney*100);
if(leftOtherPeopleMoney < otherPeopleNeedMoney){
randomMoney -= otherPeopleNeedMoney - leftOtherPeopleMoney;
}
integerRemainMoney = integerRemainMoney - randomMoney;
remainMoney = (double)(integerRemainMoney/100.0);
remainPeople--;
money = (double)(randomMoney/100.0);
return money;
}
}
public class Example8_23{
public static void main(String[] args){
try{ RedEnvelope redEnvelope = new RandomRedEnvelope(5.20,5);
System.out.printf("以下用于循环输出%d个人抢%.2f元的随机红包:\n",redEnvelope.remainPeople,redEnvelope.remainMoney);
showProcess(redEnvelope);
}
catch(java.io.IOException e){
System.out.println(e.getMessage());
}
}
public static void showProcess(RedEnvelope redEnvelope){
double sum = 0;
while(redEnvelope.remainPeople>0){
double money = redEnvelope.giveMoney();
System.out.printf("%.2f\t",money);
sum = sum + money;
}
System.out.printf("\n%.2f元的红包被抢完",sum);
}
}
这是一个通过random模拟抢红包的程序,要保证每个人至少都抢到0.01元 请问下 是红字部分出了错吗。。为什么我无论定义多少个人去抢都是报错说没有声明或捕获异常??还是构造方法中抛异常的条件出了问题??但是那个条件是我根据书上打的 应该没错呀 以及,为啥绿字不能直接写成Random random = new Random();放在构造函数里面?