(1) 设计一个复数运算接口OperatorListener,定义抽象方法Complex add(Complex z)
(2) 设计一个复数类Complex,此复数类实现OperatorListener接口,该类定义
私有属性:实部,虚部
方法:返回此复数的详细信息String toString(),输出格式例如3+4i
实现接口里的Complex add(Complex stu)抽象方法,实现复数的相加
构造方法:有参构造方法初始化成员变量
(3) 设计测试类Test,主函数要求产生两个复数对象,对象的成员变量值来自命令行参数,调用add方法,实现两个复数的相加,把相加的结果值写入到c:/ComputeInfo.txt文件中,并处理所有的异常信息。
自己写的源代码:
(1)
public interface OperatorListener{
public Complex add(Complex z);
}
(2)
public class Complex implements OperatorListener{
private double real;
private double imag;
public Complex(){
}
public Complex(double real,double imag){
this.real=real;
this.imag=imag;
}
public Complex(Complex c){
real=c.real;
imag=c.imag;
}
public double getReal(){
return real;
}
public double getImag(){
return imag;
}
public String toString(){
System.out.println(real+"+"+imag+"i");
return null;
}
public Complex add(Complex stu){
Complex p=new Complex();
p.real=real+stu.getReal();
p.imag=imag+stu.getImag();
return p;
}
}
(3)
import java.io.*;
public class Test {
public static void main(String[] args){
// TODO 自动生成的方法存根
try{
double x1,y1;
double x2,y2;
x1=Double.parseDouble(args[0]);
y1=Double.parseDouble(args[1]);
x2=Double.parseDouble(args[2]);
y2=Double.parseDouble(args[3]);
Complex com1=new Complex(x1,y1);
Complex com2=new Complex(x2,y2);
Complex com=com1.add(com2);
File f=new File("C:\ComputeInfo.txt");
FileOutputStream file=new FileOutputStream(f,true);
file.write(com.toString().getBytes("utf-8"));
file.close();
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("你还没有输入呢,请输入数值!");
}
catch(NumberFormatException e){
System.out.println("你输入的是字符,请输入数值!");
}
catch(IOException e){
System.out.println("写入文件不成功!");
}
}
}
在eclipse上可以显示结果,但是下面多出了两行:
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:16)
问题出在了file.write(com.toString().getBytes("utf-8")); 这一行
也无法写入到指定文件,想求教下这一行怎么改?