1.枚举类
1.1定义
将一个一个具体固定的对象在类中实例化例举出来叫做枚举
1.2使用
使用关键字enum创建类,枚举内容以逗号隔开
例:创建枚举类
public enum Color { red,green,yellow }
创建枚举实现方法类:
public void colorSho(Color color) {
switch (color) {
case red:
System.out.println("颜色为红色");
break;
case green:
System.out.println("颜色为绿色");
break;
case yellow:
System.out.println("颜色为黄色");
break;
}
}
整体代码及实现结果:
public class colorStu {
public void colorSho(Color color) {
switch (color) {
case red:
System.out.println("颜色为红色");
break;
case green:
System.out.println("颜色为绿色");
break;
case yellow:
System.out.println("颜色为黄色");
break;
}
}
public static void main(String[] args) {
colorStu c = new colorStu();
c.colorSho(Color.red);
}
}
运行结果:
2.包装类
2.1定义
包装类把基本类型数据转换为对象,提供了一系列方法
Java包含8种基本数据类型:整型(byte、short、int、long)、浮点型(float、double)、布尔型boolean、字符型char,相应的Java提供了8种包装类Byte、Short、Integer、Long、Float、Double、Boolean、Character。
2.2常用构造方法
所有包装类都可将与之对应的基本数据类型作为参数,来构造它们的实例
public Type(type value)
如:
String str11 = new String(“hello world”);
Integer i=new Integer(100);
除Character类外,其他包装类可将一个字符串作为参数构造它们的实例
public Type(String value)
String s=“100”;
//String类型转化为int
Integer i=new Integer(s);
注意事项!
Boolean类构造方法参数为String类型时,若该字符串内容为true(不考虑大小写),则该Boolean对象表示true,否则表示false.
当Number包装类构造方法参数为String 类型时,字符串不能为null,且该字符串必须可解析为相应的基本数据类型的数据,否则编译不通过,运行时会抛出NumberFormatException异常.
2.3包装类常用方法
1.xxxValue():包装类转换成基本类型
例:
Integer inter=new Integer(15);
int inter1= inter.intValue();
2.toString():以字符串形式返回包装对象表示的基本类型数据(基本类型->字符串)
String id=Integer.toString(25);
System.out.println(id);
3.parseXXX():把字符串转换为相应的基本数据类型数据(Character除外)(字符串->基本类型)
int num=Integer.parseInt(“36”);
System.out.println(num);
Float num1=Float.parseFloat(“12.4”);
System.out.println(num1);
4.valueOf():
所有包装类都有如下方法(基本类型->包装类)
public static Type valueOf(type value)
Integer intValue = Integer.valueOf(21);
除Character类外,其他包装类都有如下方法(字符串->包装类)
public static Type valueOf(String s)
Integer intValue = Integer.valueOf(“21”);
2.4装箱拆箱
基本类型和包装类的自动转换
装箱:基本类型转换为包装类的对象
拆箱:包装类对象转换为基本类型的值
例:
Integer intObject = 5;
int intValue = intObject;
3.Math类
3.1概念
java.lang.Math类提供了常用的数学运算方法和两个静态常量E(自然对数的底数)和PI(圆周率)
3.1Math静态常量
System.out.println(“E 常量的值:” + Math.E);
System.out.println(“PI 常量的值:” + Math.PI);
3.2Math类常用方法
System.out.println(Math.abs(-100));//绝对值
System.out.println(Math.abs(100));//绝对值
System.out.println(Math.max(101,100));//比较返回最大值
System.out.println(Math.min(101,99));//比较返回最小值
for (int i=0;i<10;i++){
double random =Math.random();
int j=(int)(random*10);
System.out.println(Math.random());//返回(0-1)之间的随机数
System.out.println("[0-9]之间的整数:"+j);
}