编程:写一个复数类(类名为:Complex),包含:①两个protected整型属性,分别代表:实数部分、虚数部分;②两个构造方法:一个带两个参数,一个不带参数;③两个方法:求实数加法的complexAdd(Complex a)方法,能把当前复数对象的实部、虚部组合成a+bi的字符串形式的String toString( )方法;④在main( )方法中对该复数类进行如下功能验证:调用complexAdd( )方法把1+2i 和3+4i 相加产生一个新的复数4+6i,调用toString( )方法把新复数转换成字符串“4+6i”,然后用System.out.println( )方法输出该字符串。
代码实现:
import java.util.*;
class Main{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
String str1=sc.nextLine();
String str2=sc.nextLine();
int k=0,l=0;
for(int i=0;i<str1.length();i++){
if(str1.charAt(i)=='+'){ //找到'a+bi'字符串中的'+'字符所在位置,下同
k=i;
break;
}
}
int real1=Integer.parseInt(str1.substring(0,k)); //把'+'之前的字符串用整数数出来(即实部的值),下同
int imag1=Integer.parseInt(str1.substring(k+1,str1.length()-1)); //把'+'之后的字符串用整数数出来(即虚部的值),下同
for(int i=0;i<str2.length();i++){
if(str2.charAt(i)=='+'){
k=i;
break;
}
}
int real2=Integer.parseInt(str2.substring(0,k));
int imag2=Integer.parseInt(str2.substring(k+1,str2.length()-1));
Complex complex1=new Complex(real1,imag1); //new一个Complex对象
Complex complex2=new Complex(real2,imag2);
complex1.complexAdd(complex2); //调用对象Complex中的complexAdd函数
System.out.println(complex1); //调用对象Complex中的toString函数
}
}
}
class Complex{
protected int real;
protected int imag;
public Complex(){
}
public Complex(int real,int imag){ //赋值函数
this.real=real;
this.imag=imag;
}
public void complexAdd(Complex c){ //想加函数,不用返回值,直接对对象操作
this.real=this.real+c.real;
this.imag=this.imag+c.imag;
}
public String toString(){ //输出函数
return this.real+"+"+this.imag+"i";
}
}