Java 语言的两个基本的元素是类(class)和接口(interface),现在Tiger又引入了枚举(enum).
其实枚举也不能算是严格意义上的新元素,它也是一种类,是一种特殊的类.所有的枚举都默认继承自java.lang.Enum,如果所有的类都默认继承自java.lang.Object一样.在Java提供的枚举中提供了比C/C++更多的功能,在这里可以像一般的类一样定义方法和属性,也可以有受限的构造函数(只能是private,且默认如此).
下面试写了一个枚举,以供参考.
package kb.enums;
public enum Temperature {
VeryHigh(100.0), //!这样使用构造函数
High,
LessComfortable,
Comfortable(25.0), //构造函数
MoreComfortable,
Low,
VeryLow(-15.0); //构造函数
private double degree;
Temperature( double d ) { //private
degree = d;
}
Temperature() {
degree = -1.0;
}
public static String getMemberList() {
StringBuffer buf = new StringBuffer();
for( Temperature t : Temperature.values() ) {
buf.append( t.toString() + "\n" );
}
return buf.toString();
}
}
package kb.enums;
public class UseTemperature {
private static StringBuffer out = new StringBuffer();
public static void main(String[] args) {
Temperature temp = Temperature.High;
switch( temp )
{
case Comfortable:
out.append( Temperature.Comfortable.toString() + "\n" );
break;
default:
out.append( "Uncomfortable\n" );
break;
}
out.append( Temperature.getMemberList() );
System.out.print( out.toString() );
}
}
class complex
{
double real,imag;
complex () {}
complex(double r,double i)
{ real=r;
imag=i;
}
complex addition(complex x,complex y)
{ this.real=x.real+y.real;
this.imag=x.imag+y.imag;
return(this) ;
}
complex subtraction(complex x,complex y)
{ this.real=x.real-y.real;
this.imag=x.imag-y.imag;
return(this) ;
}
complex multiplication(complex x,complex y)
{ this.real=(x.real)*(y.real)-(x.imag)*(y.imag);
this.imag=(x.real)*(y.imag)+(x.imag)*(y.real);
return(this) ;
}
complex division(complex x,complex y)
{ this.real=((x.real)*(y.real)+(x.imag)*(y.imag))/((y.real)*(y.real)+(y.imag)*(y.imag));
this.imag=((x.imag)*(y.real)-(x.real)*(y.imag))/((y.real)*(y.real)+(y.imag)*(y.imag));
return(this) ;
}
}
public class C
{
public static void main(String args[])
{
complex c1=new complex(2,4);
complex c2=new complex(4,8);
complex c=new complex();
c.addition(c1,c2);
System.out.println("c=c1(2,4)+c2(4,8)"+" "+c.real+","+c.imag);
c.subtraction(c1,c2);
System.out.println("c=c1(2,4)-c2(4,8)"+" "+c.real+","+c.imag);
c.multiplication(c1,c2);
System.out.println("c=c1(2,4)*c2(4,8)"+" "+c.real+","+c.imag);
c.division(c1,c2);
System.out.println("c=c1(2,4)/c2(4,8)"+" "+c.real+","+c.imag);
}
}
name C.java
运行结果:c=c1(2,4)+c2(4,8) 6.0 ,12.0
c=c1(2,4)-c2(4,8) -2.0 ,-4.0
c=c1(2,4)*c2(4,8) -24.0,32.0
c=c1(2,4)/c2(4,8) 0.5,0.0
求助:为什么我在函数中用getReal,getImag分别返回各函数的实部和虚部实现不了?
摘要: 一共三个文件: ComplexException.java : Complex类所应的异常 Complex.java : Complex类...
阅读全文
据我感觉好像进度很慢啊,这么久了连一篇学习日记都没有写,所以今天我提了个问题,看看谁做的好些。还有可以的话在后面简要地说说各位的进度如何,老是没反应我就觉得好像都跟我一样呢