问答题 编写一个完整的Java Applet 程序使用复数类Complex验证两个复数 1+2i 和3+4i 相加产生一个新的复数 4+6i 。
复数类Complex必须满足如下要求:
(1) 复数类Complex 的属性有:
RealPart : int型,代表复数的实数部分
ImaginPart : int型,代表复数的虚数部分
(2) 复数类Complex 的方法有:
Complex( ) : 构造函数,将复数的实部和虚部都置0
Complex( int r , int i ) : 构造函数,形参 r 为实部的初值,i为虚部的初值。
Complex complexAdd(Complex a) : 将当前复数对象与形参复数对象相加,所得的结果仍是一个复数值,返回给此方法的调用者。
String ToString( ) : 把当前复数对象的实部、虚部组合成 a+bi 的字符串形式,其中a 和 b分别为实部和虚部的数据。

【正确答案】import java.applet.* ;
import java.awt.* ;
public class abc extends Applet
{
Complex a,b,c ;
public void init( )
{
a = new Complex(1,2);
b = new Complex(3,4);
c = new Complex();
}
public void paint(Graphics g)
{
c=a.complexAdd(b);
g.drawString("第一个复数:"+a.toString(),10,50);
g.drawString("第二个复数:"+b.toString(),10,70);
g.drawString("两复数之和:"+c.toString(),10,90);
}
}
class Complex
{
int RealPart ; // 复数的实部
int ImaginPart ; // 复数的虚部
Complex() { RealPart = 0 ; ImaginPart = 0 ; }
Complex(int r , int i)
{ RealPart = r ; ImaginPart = i ; }
Complex complexAdd(Complex a)
{
Complex temp = new Complex( ); // 临时复数对象
temp.RealPart=RealPart+a.RealPart;
temp.ImaginPart=ImaginPart+a.ImaginPart;
return temp;
}
public String toString( )
{ return ( RealPart+" + "+ImaginPart+" i "); }
}
Java线程 程序题
class sum implements Runnable {
int sum = 0;
int i;
public void run () {
for(i=1;i<=100;i++) {
sum+=i;
}
System.out.println("从1加到100的结果为"+sum);
}
}
class sumpro {
public static void main(String args[]) {
sum sum1 = new sum();
Thread t=new Thread(sum1);
t.start();
}
}
异常
1.import java.io.*;
class A{
void m() throws RuntimeException{}
}
class B extends A{
void m() throws IOException{}
}
2.import java.io.*;
class A{
void m() throws RuntimeException{}
}
class B extends A{
void m() throws IOException{}
}
3.public class e8{
public static void main(String args[]){
e8 t=new e8();
t.first();
System.out.println(“Hi");
}
public void first(){second();}
public void second() throws Exception{
int x[]=new int[2];
x[3]=2;
}
}
4.public class e10{
public static void main(String args[]) throws Exception{
e10 t=new e10();
t.first();
System.out.println(“Hi");
}
public void first() throws Exception{second();}
public void second() throws Exception{
int x[]=new int[2];
x[3]=2;
}
}
5.使用super调用父类方法
class Fish extends Animal{
public Fish(){super(0);}
public void eat(){
System.out.println("鱼吃小鱼虫");
}
public void walk(){
super.walk();
System.out.println("鱼没有腿不会走路");
}
}
6.接口类的实现
class Cat extends Animal implements Pet{
String name;
public Cat(String n){
super(4);
name=n;
}
public Cat(){this("");}
public String getName(){return name;}
public void setName(String n){name=n;}
public void play(){
System.out.println("猫玩耍");
}
public void eat(){
System.out.println("猫吃猫粮");
}
}
【答案解析】