?? fushutestyichang.java
字號:
//FushuTestyichang.java
class LessParamException extends Exception {
private int inputNum; //用戶輸入的參數(shù)數(shù)目
public LessParamException(int a) {inputNum=a;}
public int getInputNum( ) {return inputNum;}
public void handleException( ) {
System.out.println("需要輸入5個參數(shù),您只輸入了"+getInputNum()+"個參數(shù),程序中止。請再次運行程序時注意");
}
}
class NoOpertaionException extends Exception { //自定義的運算符異常
public NoOpertaionException( ){}
public void handleException( ){
System.out.println("缺乏操作符。請輸入+、-、x、\\ 之一進行運算!");
}
}
class DividedByZeroException extends Exception {//自定義除數(shù)為零的異常
public DividedByZeroException( ){ }
public void handleException( ){
System.out.println("除數(shù)為零,請重新輸入除數(shù)!");
}
}
class Fushu{ //復數(shù)類
private float x,y;
public float getShibu(float x){ return x;} //獲得實部方法
public float getXubu(float y){ return y;}//獲得虛部方法
public String showFushu( ) { return x+"+"+y+"i"; }//顯示復數(shù)
public Fushu add(Fushu f){//加法
float a=this.x+f.x;
float b=this.y+f.y;
Fushu Result=new Fushu(a,b);
return Result; }
public Fushu minus(Fushu f){//減法
float a=this.x-f.x;
float b=this.y-f.y;
Fushu Result=new Fushu(a,b);
return Result; }
public Fushu mult(Fushu f){//乘法
float a=this.x*f.x-this.y*f.y;
float b=this.x*f.y+this.y*f.x;
Fushu Result=new Fushu(a,b);
return Result; }
public Fushu divd(Fushu f) throws DividedByZeroException {//除法,聲明拋出除數(shù)為0異常
if(f.x==0) throw new DividedByZeroException(); //若除數(shù)為0則拋出異常
else {
float a=(this.x*f.x+this.y*f.y)/(f.x*f.x+f.y*f.y);
float b=(this.y*f.x-this.x*f.y)/(f.x*f.x+f.y*f.y);
Fushu Result=new Fushu(a,b);
return Result;}
}
public Fushu(float x,float y){//復數(shù)的構造方法
this.x=x;
this.y=y;}
}
public class FushuTestyichang {//主類
public static void main(String[] args){
try{
if (args.length<5) throw new LessParamException(args.length);//拋出缺少參數(shù)異常
//以下將args參數(shù)轉(zhuǎn)換為float型后,構造出2個復數(shù)對象并顯示:
Fushu f1=new Fushu(Float.parseFloat(args[0]), Float.parseFloat(args[1]));
Fushu f2=new Fushu (Float.parseFloat(args[2]), Float.parseFloat(args[3]
));
System.out.println("您輸入的復數(shù)是:");
System.out.println("f1="+f1.showFushu()); //顯示復數(shù)
System.out.println("f2="+f2.showFushu()); //顯示復數(shù)
//以下判斷運算符
if (args[4].equals("+"))
{System.out.println("The sum="+f1.add(f2).showFushu());} //f1+f2
else if (args[4].equals("-"))
{System.out.println("The differs="+f1.minus(f2).showFushu());} //f1-f2
else if (args[4].equals("x"))
{System.out.println("The product="+f1.mult(f2).showFushu());} //f1xf2
else if (args[4].equals("\\"))
{System.out.println("The quotient="+f1.divd(f2).showFushu());} //f1\f2
else {throw new NoOpertaionException();}//拋出運算符錯誤的異常
}
catch(LessParamException e1) {e1.handleException( );}
catch(DividedByZeroException e2) {e2.handleException( );}
catch(NoOpertaionException e3) {e3.handleException( ); }
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -