异常类
try-catch语句处理异常类
将可能出现的异常放在try部分,一旦try部分抛出异常对象,或调用某个可能抛出异常对象的方法,并且该方法抛出了异常对象,那么try部分将立刻结束执行,转向catch部分。所以将发生异常后的处理部分放在catch部分。
import java.io.IOException;
public class Test1 {
public static void main(String args[]){
int n=0,m=0,t=1000;
try{
m= Integer.parseInt("8888");
n=Integer.parseInt("ab89");//发生异常,转向catch
t=7777;//t没有机会被赋值
}
catch(NumberFormatException e){
System.out.println("发生异常:"+e.getMessage());
}
System.out.println("n="+n+",m="+m+",t="+t);
try{
System.out.println("故意抛出I/O异常!");
throw new IOException("我是故意的");//故意抛出异常
//System.out.println("这个输出语句肯定没机会执行,必须注释,否则编译出错");
}
catch(IOException e){
System.out.println("发生异常:"+e.getMessage());
}
}
}
throw关键字,抛出异常
断言
在调试代码阶段非常有用,断言语句一般用于程序不准备通过捕获异常来处理的错误
assert关键字
1.格式:
1.assert booleanExpression;
2.assert booleanExpression:messageException;
- 在使用Java解释器直接运行应用程序时,默认的关闭断言语句,在调试程序时可以使用 -ed 启用断言语句。
常用实体类
1.string类
- 创建一个字符串变量
1.public intlength() 可以获取一个字符串的长度
2.public boolean equals (String s) 比较当前字符串对象的实体是否与参数s指定的字符串实体相同。
3.public boolean startsWith(String s),public boolean endsWith(String s) 字符串对象调用 StartsWith(String s),当判断当前字符串对象的前缀是否是参数s指定的字符串
4.public int compareTO(String s) 按字典序与参数s 指定的字符串比较大小。如果当前字符串与s相同,该方法返回值0;如果当前字符串对象大于s,该字符串返回正值;如果小于s,该方法返回负值。
5.public boolean contains(String s) 字符串对象调用contains方法判断当前字符串对象是否含有参数指定的字符串s
6.pubic int indexOf(String s) 从当前字符串的头开始检索字符串s,并返回首次出现s的索引位置。
7.public String substring(int starpoint) 字符串对象调用该方法获得一个当前字符串的子串,该子串是从当前字符串的startpoint出截取到最后所得到的字符串。
8.public String trim() 一个字符串s通过调用方法trim()得到一个字符串对象,该字符串对象是s去掉当前空格后的字符串。
2.scanner类
- 从字符串中解析出程序所需要的数据
import java.util.*;
public class E {
public static void main(String args[ ]){
String cost ="Tv coast 88dollar.Computer cost 342 dollar";
Scanner scanner =new Scanner(cost);
double sum =0;
while(scanner.hasNext()){
try {
double price = scanner .nextDouble();
sum = sum+price;
System.out.println(price);
}
catch(InputMismatchException exp){
String t = scanner.next();
}
}
System.out.println("总消费:"+sum+"元");
}
}
3.Date与Calendar类
- 用于时间,日期等数据的处理
4.Math类
- 用于计算一个数平方根,绝对值或获取一个随机数等。
Integer类
- Integer类,封装基本数据类型int,提高大量方法
- 将字符串转成基本数据类型int
- int => String 任何类型 +“ ”变成String类型
- Integer类中的静态方法toString()
public class INtegerDemo{
public static void main(String[ ] args){
function_2( );
}
public ststic void function_2( ){
int i=3;
String s=i+" " ;
System.out.println(s+1);
String s1 =Integer.toString(5,2); //把5转成二进制
System.out.println(s1 );
}
}
输出: 101
Integer类的构造方法
Integer (String s)
将数字格式的字符串,传递到Integer类的放、构造方法中
创建Integer对象,包装一个字符串
将构造方法的字符串,转成基本数据类型,调用方法,非静态的,intValue()
public static void function_3(){
Integer in = new INteger("100");
int i= in.inValue();
System.out.println(--i);
}