第三次Java基础知识复习

第四章面向对象

异常

      在程序运行的过程中,也会发生各种非正常状况,比如程序运行时磁盘空间不足、网络连接中断、被装载的类不存在等。在Java语言中,引入异常,以异常类的形式对这些非正常情况进行封装,通过异常处理机制对程序运行时发生的各种问题进行处理。 

      Throwable有两个直接子类Error和Exception,其中Error代表程序中错误,Exception代表程序中产生的异常。

try...catch和finally

      Java中提供了一种异常进行处理的方式——异常捕获。异常捕获通常使用try...catch语句,语法格式如下:

try{

//程序代码块

}catch (ExceptionType(Exception 类及其子类)e){

//对ExceptionType的处理

}

      其中在try代码块中编写可能发生异常的Java语句,catch代码块中编写针对异常进行处理的代码。当try代码块中的程序发生了异常,系统会将这个异常的信息封装成一个异常对象,并将这个对象传递给catch代码块。catch代码块需要一个参数指明它所能够接收的异常类型,这个参数的类型必须是Exception类或其子类。

 代码案例。代码如下:

public class Example {
	public static void main(String[] args) {
		//下面的代码定义一个try...catch...finally语句用于捕获异常
		try {
		int result=divide(4,0);//调用divide()方法
		System.out.println(result);
		}catch(Exception e) {//对异常进行处理
			System.out.println("捕获的异常信息为:"+e.getMessage());
			return;//结果整个方法
	}finally {
		System.out.println("进入finally代码块");
	}
		
		System.out.println("程序继续向下执行");
}
//下面方法实现了两个整数相除
	public static int divide(int x,int y) {
		int result=x/y;//定义变量result记录两个数相处的结果
		return result;
	}
}

运行结果:

 throws关键字

       Java中允许在方法的后面使用throws关键字对外声明该方法有可能发生的异常,这调用者在调用方法时,就明确地知道该方法有异常,并且必须在程序中对异常进行处理,否则编译无法通过。

throws关键字声明抛出异常的语法格式如下:
修饰符 返回值类型 方法名 ([参数1,参数2....])throws ExceptionTypel[,ExceptionType2.....]{

}

      throws关键字需要在声明后面, throws后面需要声明方法中发生异常的类型,通常将这种做法称为方法声明抛出一个异常。

public class Example {
 
public static void main(String[] args) throws Exception{
//下面的代码定义了一个try...catch语句用于捕获异常
try {
int result=divide(4,2);//调用divide()方法
System.out.println(result);
}catch(Exception e) {//对捕获的异常进行处理
e.printStackTrace();//打印捕获的异常信息
}
}
//下面的方法实现了两种整数相除,并使用throws关键字声明抛出异常
public static int divide(int x,int y)throws Exception{
int result=x/y;//定义变量result记录两个数相除的结果
return result;
}
}

运行结果:

 运行时异常和编译时异常

1、编译异常 

      在Java中,Exception类中除了RuntimeException类及其子类都是编译时异常。编译时异常的特点是Java编译会对其进行检查,如果出现异常就必须对异常进行处理,否则程序无法通过编译。处理编译时期的异常有两种方式: 

  • 使用try...catch语句对异常进行捕获
  • 使用throws关键字声明抛出异常,调用者对其处理

 2、运行异常

       RuntimeException类及其子类都是运行时异常。运行时异常的特点是Java编译器不会对其进行检查,当程序中出现这类异常时,即使没有使用try...catch语句捕获或使用throws关键字声明抛出,程序也能编译通过。运行时异常一般是由程序中的逻辑错误引起的,在程序运行时无法恢复。

自定义异常

       JDK中定义了大量的异常类,虽然这些异常类可以描述编程时出现的大部分异常情况,但在程序开发中有时可能需要描述程序中特有的异常情况。

自定义异常
package W;
//下面的代码是自定义一个异常类继承Excption
public class DivideByMinusExcption extends Exception{
public DivideByMinusExcption() {
super ();//调用Excption无参构造方法
}
public DivideByMinusExcption(String message) {
super(message);
}
}
 
package W;
public class Excption {
public static void main(String[] args) {
int result=divide(4,-2);//调用divide()方法,传入一个负数作为被除数
System.out.println(result);
}
//下面的方法实现了两种整数相除
public static int divide(int x,int y){
if (y<0) {
//throw new DivideByMinusExcption("除数是负数");//使用throw关键字抛出异常对象
}
int result=x/y;//定义变量result记录两个数相除的结果
return result;
}
}
 
 
package W;
 
public class Excption2 {
 
public static void main(String[] args) {
try {
int result=divide(4,-2);//调用divide()方法,传入一个负数作为被除数
System.out.println(result);
}catch (DivideByMinusExcption e) {//对捕获的异常进行处理
System.out.println(e.getMessage());//打印捕获的异常信息
}
 
}
//下面的方法实现了两种整数相除,使用throws关键字声明抛出异常
public static int divide(int x,int y)throws DivideByMinusExcption{
if (y<0) {
throw new DivideByMinusExcption("除数是负数");//使用throw关键字抛出异常对象
}
int result=x/y;//定义变量result记录两个数相除的结果
return result;
}
}
 
自定义异常
package W;
//下面的代码是自定义一个异常类继承Excption
public class DivideByMinusExcption extends Exception{
public DivideByMinusExcption() {
super ();//调用Excption无参构造方法
}
public DivideByMinusExcption(String message) {
super(message);
}
}
 
package W;
public class Excption {
public static void main(String[] args) {
int result=divide(4,-2);//调用divide()方法,传入一个负数作为被除数
System.out.println(result);
}
//下面的方法实现了两种整数相除
public static int divide(int x,int y){
if (y<0) {
//throw new DivideByMinusExcption("除数是负数");//使用throw关键字抛出异常对象
}
int result=x/y;//定义变量result记录两个数相除的结果
return result;
}
}
 
 
package W;
 
public class Excption2 {
 
public static void main(String[] args) {
try {
int result=divide(4,-2);//调用divide()方法,传入一个负数作为被除数
System.out.println(result);
}catch (DivideByMinusExcption e) {//对捕获的异常进行处理
System.out.println(e.getMessage());//打印捕获的异常信息
}
 
}
//下面的方法实现了两种整数相除,使用throws关键字声明抛出异常
public static int divide(int x,int y)throws DivideByMinusExcption{
if (y<0) {
throw new DivideByMinusE

运行结果: 

 访问控制

      在Java中,针对类、成员方法和属性提供了四种访问级别,从小打到大分别是private、deafault、protected和public。

展示了Java中的四种访问控制级别,具体介绍如下:

  • private(类访问级别):如果类中的成员被private访问控制符来修饰,则这个成员只能被该类的其他成员访问,其他类无法直接访问。类的良好封装就是通过private关键字来实现的。
  • default(包访问级别):如果一个类或者类的成员不使用任何访问控制符修饰,则称它默认访问控制级别,这个类或者类的成员只能被本包的其它类访问问。
  • protected(子类访问级别):如果一个类的成员被protected访问控制修饰符,那么这个成员既能被同一包下的其他类访问,也能被不同包下该类的子类访问。
  • public(公共访问级别):这是一个最宽松的访问控制级别,如果一个类或者类的成员被pubic访问控制符修饰,那么这个类或者类的成员能被所有的类访问,不管访问类与被访问类是否在同一个包中。

第五章JavaAPI类的初始化

String类和StringBuffer类的使用

       API(Application Programming Interface)指的是应用程序编程接口。假设使用Java语言编写一个机器人程序去控制机器人踢足球,程序就需要向机器人发出向前跑、向后跑、射门、抢球等各种命令,没有编过程序的人很难想象这样 的程序如何编写。但是对于有经验的开发人员来说知道机器人厂商一定会提供一些用于控制机器人的Java类,这些类中定义好了操作机器人各种动作的方法。其实,这些Java类就是机器人厂商提供给应用程序编程的接口,通常把这些类称为Xxx Robot API(意思是Xxx厂家的机器人API)。

     在应用程序中经常会用到字符串,所谓字符串就是指一连串的字符,它是由许多单个字符连接而成的,如多个英文字母所组成的一个英文单词。字符串中可以包含任意字符,这些字符必须包含在一对双引号“”之内,例如“abc”。在Java中定义了String和StringBuffer两个类来封装字符串,并提供了一系列操作字符串的方法,它们都位于java.lang包中,因此不需要导包就可以直接使用。
 

 String类的常见操作

string类在实际开发中的应用非常广泛,因此灵活地使用string类是非常重要的,接下来介绍string类常用的一些方法如下表所示。


/*
 * String类的基本操作
 * 在程序中,需要对字符串进行一些基本操作,如获取字符串长度,获取指定位置的字符等
 * public int length() 获取字符串的长度
 * public char charAt(int index) 获取字符串中指定位置上的字符 
 * public int  indexof(char ch) 获取指定字符在字符串中第一次出现的位置
 * public int lastIndexof(char ch)获取指定字符在字符串中最后一次出现的位置
 * public int indexof(String str)获取指定子串在字符串中第一次出现的位置
 * public int lastIndexof(String str)获取指定子串在字符串中最后异常出现的位置
 */
public class Example {
 public static void main(String[] args) {
  //声明一个字符串
  String s="abcabcdebca";
  System.out.println("获取字符串的长度:"+s.length());
  System.out.println("获取字符串中第一个字符:"+s.charAt(0));
  System.out.println("获取字符c第一次出现的位置:"+s.indexOf('c'));
  System.out.println("获取字符c最后一次出现的位置:"+s.lastIndexOf('c'));
  System.out.println("获取子串ab第一次出现的位置:"+s.indexOf("ab"));
  System.out.println("获取子串ab最后一次出现的位置:"+s.lastIndexOf("ab"));
 }
}

运行结果: 

 

字符串进行转换操作:

案例一:

/*
 * String类的转换操作
 * 在程序开发中,经常需要对字符串进行转换操作,例如将字符串转换成数组的形式,将字符串的进行大小写转换等
 * public char[]tochatArray()将此字符串转换成字符数组
 * public static String valueof(int n)将指定int值转换成String类型
 * public String touppercase() 将此字符串中的字符全部转换成大写字母,会返回一个新的字符串
 */
public class Example {
 public static void main(String[] args) {
 //声明一个字符串
  String s="abcde";
  //将此字符串转换成字符数组
  char[] charArray=s.toCharArray();
  for (int i=0;i<charArray.length;i++) {
   //a,b,c,d,e
   if(i==charArray.length-1) {
    //数组最后一个元素,直接打印元素
    System.out.println(charArray[i]);
   }else {
    //打印元素值与逗号
    System.out.print(charArray[i]+",");
   }    
   }
  System.out.println("将指定int值转换成String类型后的结果"+String.valueOf(12));
  System.out.println("将字符串转换成大写字母的结果:"+s.toUpperCase());
    }
}

运行结果:

 案例二:

public class Example {
 /*
  * String类的替换与去除空格操作
  * 程序开发中,用户输入数据时经常会有一些错误和空格,这时可以使用String类的replace()和trim()方法,进行字符串的替换和去除空格操作。
  *  public String replace(String oldStr, String newStr)
  *  将原有字符串中o1dStr字符串内容用newStr字符串所替代,返回一个新的字符串
  *  public String trim() 返回一个新字符串,它去除了原有字符串的两端空格
  */
 
 public static void main(String[] args) {
  //声明一个字符串
   String s="itcast";
   String s2="i t c a s t  ";
  //者换操作
   System.out.println("将it替换成cn.it之后的结果:"+ s.replace("it","cn.it"));
  //去除空格操作
   System.out.println("去除左右两边空格后的结果:"+ s2.trim());
   System.out.println("去除全部空格后的结果:"+s2.replace(" ",""));
 }
}

运行结果:

 案例三:


//判断字符串是否以指定的字符串开始与结束,是否包含指定字符串是否为空等
/*
* string类的判断操作
* 操作字符串时,经常需要对字符串进行一些判断,如判断字符串是否以指定的字符串开始、结束,是否包含指定的字符串,字符串是否为空等。
* public boolean startsWith(String stx)判断字符串是否以给定字符串stx开头
* public boolean endswith(Stringstx)判断字符串是否以给定字符串stx结尾
* public boolean contains(String str)判断字符串是否包含给定的字符串stx
* public boolean isEmpty()判断字符串内容是否为空
* public boolean equals(String stx)判断字符串与给定字符串stx的内容是否相同
*/
public class Example {
public static void main(String[] args) {
//声明一个字符串
String s="String";
String s2 ="Str";
System.out.println("判断字符串是否以Str开头:"+s.startsWith("Str"));
System.out.println("判断字符串是否以ng结尾:"+s.endsWith("ng"));
 System.out.println("判断字符串是否包含tri:"+ s.contains("tri"));
 System.out.println("判断当前字符串内容是否为空:"+s.isEmpty());
 System.out.println("判断两个字符串中的内容是否相同:"+ s.equals(s2));
}
}

运行结果:

 案例四:

//字符串的截取和分割操作
/*
* String类的截取与分割操作
* 在String类中针对字符串的截取和分割操作提供了两个方法
* 其中,substring()方法用于截取字符串的一部分
* split()方法可以将字符串按照某个字符进行分割
* public String substring(int start)返回一个新字符串,它从原有字符串指定位置开始截取,到字符串末尾结束
* public String substring(intstart, int end) 返回一个新字符串,它从原有字符串指定位置开始截取,到指定位置结束
* public String[] split(String regex)按照指定的字符串进行分割返回一个字符串数组
* 
*/
public class Example{
private static int i;
public static void main(String[] args) {
//声明一个字符串
String s="羽毛球一篮球一乒乓球";
//截取操作
System.out.println("从第5个字符开始截取到末尾的结果:"+ s.substring(4));
System.out.println("从第5个字符开始截取到第6个字符结束的结果:"+s.substring(4,6));//不包含结尾位置的字符
//分割操作
System.out.println("打印分割后的每个字符串内容"); 
String[] strArray = s.split("-");
for (int i= 0; i< strArray.length; i++);{
// 羽毛球,篮球,乒乓球
if (i== strArray.length -1) {
//数组最后一个元素,直接打印数组元素值
System.out.println( strArray[i]);
}else {
 //打印数组元素值与逗号
  System.out.print( strArray[i] +","); 
}
}
}
}

运行结果:

案例五:

/*
 * String类的异常演示
 * String字符串在获取某个字符时,会用到字符的索引,当访问字符串中的字符时
 * 如果字符的索引不存在,则会发生StringIndex0utOfBoundsException(字符串角标越界异常)
 */
public class Example{
 public static void main(String[] args) {
  //声明一个字符串
  String s="abcde12345";
  System.out.println( s.charAt(10) );
 }
}

运行结果:

StringBuffer类

      由于字符串是常量,因此一旦创建,器内容和长度是不可改变的。如果需要对一个字符串进行修改,则只能创建新的字符串。为了便于对字符串进行修改,再JDK中提供了一个StringBuffer类(也称字符串缓冲区)。StringBuffer类和String类最大的区别在于它的内容和长度都是可以改变的。StringBuffer类似一个字符容器。当在其中添加或删除字符时,并不会产生新的StringBuffer对象。

针对添加和删除字符串的操作,StringBuffer类提供了一系列的方法,具体如下:

/*
 * stringbuffer的构造方法
 * public stringBuffer()空参数构造方法
 *  public stringBuffer(string data)创建带有内容的字符串缓冲区
 * 
 * stringbuffer类的常用方法
 * public stringBuffer append(string str)向字符串缓冲区的末尾添加数据,返回当前的stringBuffer对象自身
 * public stringBuffer insert(int index,string str)向字符串缓冲区指定位置上,插入指定数据
 * public stringBuffer delete(int start,int end)删除字符串缓冲区指定范围内的数据
 * public stringBuffer deleteCharAt(int index)删除字符串缓冲区内指定位置上的数据
 * public int length()获取字符串缓冲区的长度
 * public stringBuffer replace(int start,int end,string str)替换字符串缓冲区指定范围内的字符串
 *  public stringBuffer setcharAt(int index,char ch)替换字符串缓冲区指定位置上的字符
 *  public stringBuffer reverse()字符串缓冲区数据翻转方法
 */
public class Example{
  public static void main(String[] args) {
   System.out.println("1、添加----------------");
   add();
   System.out.println("2、删除----------------");
   remove();
   System.out.println("3、修改----------------");
   alter();
  }
  public static void add() {
   //定义一个字符串缓冲区
   StringBuffer sb=new StringBuffer();
   //向缓冲区的末尾添加指定字符串
   sb.append("abcdefg");
   System.out.println("append添加数据后的结果:"+sb);
   //向缓冲区指定位置插入字符串
   sb.insert(2, "123");
  System.out.println("插入数据后的结果:"+sb);
  }
  public static void remove() {
   //定义一个字符串缓冲区对象
   StringBuffer sb=new StringBuffer("abcdefg");
   //删除字符串缓冲区指定范围内的数据
   sb.delete(1, 5);//不包含结尾位置元素
   System.out.println("删除指定范围数据后的结果:"+sb);
   //删除字符串缓冲区指定位置上的字符
   sb.deleteCharAt(2);
   System.out.println("删除指定位置数据后的结果:"+sb);
  //清除字符串缓冲区
   sb.delete(0, sb.length());
   System.out.println("清除缓冲区数据后的结果:"+sb);
   
  }
  public static void alter() {
   //定义一个字符串缓冲区对象
   StringBuffer sb=new StringBuffer("abcdef");
   //修改指定位置的字符
   sb.setCharAt(1, 'p');
   System.out.println("修改指定位置数据后的结果"+sb);
   //修改指定范围内的数据
   sb.replace(1, 3, "qq");
   System.out.println("替换指定范围内字符串的结果"+sb);
   //字符串缓冲区数据翻转
   System.out.println("字符串缓冲区数据翻转后的结果"+sb.reverse());
  }
}

 运行结果:

案例  记录一个子串在整串中出现的次数

/*
 * 记录一个子串在整串中出现的次数
 * 思路:
 *  1.定义一个整串,定义一个子串
 *  2.获取子串在整串中出现的次数
 */
 
public class Example{
	public static void main(String[] args) {
		//1.定义一个整串,定义一个子串
		String str = "nbaernbatnbaynbauinbapnba";//整串
		String key = "nba";//子串
		//2.获取子串在整串中出现的次数
		int count = getKeyStringCount(str,key);
		System.out.println("count="+count);
		
	}
	//获取子串在整串中出现的次数
	public static int getKeyStringCount(String str, String key) {
		//定义计数器,用来记录出现的次数
		int count = 0;
		//如果整串中不包含子串,则直接返回count
		if(!str.contains(key)) {
			return count;
		}
		//定义变量,用来记录key出现的位置
		int index = 0;
		/*
		 * 1.查找子串在整串中出现的位置
		 * 2.将出现的位置记录在index变量中
		 */
		while((index = str.indexOf(key)) != -1) {
			//子串出现次数累加
			count++;
			//截取整串,从子串出现的位置后面开始,到整串末尾
			str = str.substring(index + key.length());
		}
		return count;
	}
}

运行结果:

 System类

       System类定义了一些与系统相关的属性和方法,它所提供的属性和方法都是静态的,想要引用这些属性和方法,直接使用 System类调用即可。

 System类的常用方法

import java.util.Properties;
import java.util.Set;
/*
 * System类的方法
 * public static Properties getProperties()
 * 方法用于获取当前系统的全部属性,该方法会返回一个Properties类型的容器
 * 其中封装了系统的所有属性,这些属性是以”属性名=属性值“的形式存在的
 * public static String getProperty(String key)
 * 	获取指定键(属性名)所对应的系统属性值
 */
public class Example{
	public static void main(String[] args) {
		//获取当前系统属性
		Properties properties = System.getProperties();
		System.out.println(properties);
		
		//获取所有系统属性的key(属性名),返回Set对象
		Set<String> PropertyNames = properties.stringPropertyNames();
		for(String key : PropertyNames) {
			//获取当前键key(属性名)所对应的值(属性值)
			String value = System.getProperty(key);
			System.out.println(key +"--->"+value);
			
		}
	}
}

运行结果:

 currentTimeMillis()

       currentTimeMillis()方法返回一个long类型的值,该值表示当前时间与1970年1月1日0点0分0秒之间差,单位时毫秒,通常也将该值称作时间数。

/*
 * public static long currentTimeMillis()
 * 方法返回一个long类型的值,该值表示当前时间与1970年1月1日0点0分0秒之间的时间差,单位是毫秒,通常也将该值称作时间戳
 */
public class Example{
	public static void main(String[] args) {
		//计算程序在进行求和操作时所消耗的时间
		
		//计算程序在进行求和操作时所消耗的事件
		long startTime = System.currentTimeMillis();
		int sum =0;
		for (int i=0;i < 100000000; i++) {
			sum+= i;
		}
		//循环结束后的当前时间
		long endTime =System.currentTimeMillis();
		System.out.println("程序运行的时间为:"+ (endTime - startTime) + "毫秒");
	}
}

运行结果:

 arraycopy(Object src,int srcPos,Object destPos,int length)

  arraycopy()方法用于将一个数组中的元素快速拷贝到另一个数组。其中的参数具体作用如下:

  • src:表示源数组
  • dest:表示目标数组
  • srcPos:表示源数组中拷贝元素的起始位置
  • destPos:表示拷贝到目标数组的起始位置
  • length:表示拷贝元素的个数

/*
 *  arraycopy(Object src,int srcPos,Object dest,int destpos,int length)
 *  arraycopy()方法用于将一个数组中的元素快速拷贝到另一个数组。其中的参数具体作用如下:
 *  src:表示源数组。
 *dest:表示目标数组。
 *srcPos:表示源数组中拷贝元素的起始位置destPos:表示拷贝到目标数组的起始位置
 *lenqth: 表示拷贝元素的个数。
 */
public class Example{
	public static void main(String[] args) {
		int[] fromArray ={101,102,103,104,105,106}; //源数组
		int[] toArray ={201,202,203,204,205,206,207}; //目标数组
		//拷贝数组元素,从fromArray数组2角标位置开始,拷贝4个素,到toArray数组3角标位置
		System.arraycopy(fromArray,2,toArray,3,4);
		//打印toArray数组中的元素
		for (int i = 0; i < toArray.length; i++) {
			System.out.println(i+":" + toArray[i]);
		}
	}
}

运行结果:

 Runtime类

 Runtime类用于表示虚拟机运行时的状态,它用于封装JVM虚拟机进程。每次使用Java命令启动虚拟机都对应一个 Runtime实例,并且只有一个实例,该类采用单例模式进行设计,对象不可以直接实例化。若想在程序中获得一个RunTime实例,只能通过以下方式:

 Runtime run= Runtime.getRuntime();

由于Runtime类封装了虚拟机进程,因此,在程序中通常会通过该类的实例对象获取当前寻虚拟的相关信息。 


/*
 * Runtime类的使用
 * public int availableProcessors()想Java虚拟机返回可以处理器的数目
 * public long freeMemory()返回Java虚拟机中的空闲内存里
 * public long maxMemory()返回Java虚拟机试图使用的最大内存量
 * public static Runtime getRuntime()返回与当前Java应用程序相关的运行时对象
 */
public class Example{
	public static void main(String[] args) {
		//获取Runtime类对象
		Runtime rt = Runtime.getRuntime();
		System.out.println("处理器的个数:"+rt.availableProcessors()+"个");
		System.out.println("空闲内容数量:"+rt.freeMemory()/1024/1024+"M");
		System.out.println("最大可用内存数量:"+rt.maxMemory()/1024/1024+"M");
	}
}

运行结果:

  Runtime类中提供了一个exec()方法,该方法用于执行一个dos命令,从而实现和在命令窗口中输入dos命令同样的效果。

import java.io.IOException;

/*
 * Runtime类中提供了一个exec()方法,该方法用于执行一个dos命令,从而实现和在命令行窗口中输入dos命令同样的效果
 */ 
 
public class Example{
	public static void main(String[] args) throws IOException {
		//获取Runtime类对象
		Runtime rt = Runtime.getRuntime();
		rt.exec("notepad.exe");//调用exec()方法,会自动打开一个记事本
	}
}
/*
 * 打开的记事本并在3秒后自动关闭
 * public Process exec(String command)在单独的进程中执行指定的字符串命令
 */
public class TrigonometricFunction{
	public static void main(String[] args) throws IOException, InterruptedException {
		//获取Runtime类对象
		Runtime rt = Runtime.getRuntime();
		
		//得到一个表示进程的procss对象
		Process process = rt.exec("notepad.exe");
		Thread.sleep(3000);//程序休眠3秒
		process.destroy();//杀掉进程
	}
}

Math类

       Math类是数学操作类,提供了一系列用于数学运算的静态方法,包括求绝对值、三绝函数等。Math类中有两个静态常量PI和E,分别代表数学常量Π和和e。

由于Math类比较简单,因此初学者可以通过查看API文档来学习Math类的具体用法。

/*
 * Math类中的常用方法
 * public static int abs(int a)返回参数的绝对值
 * public static double cell(double a)返回大于参数的最小的整数
 * public static double floor(double a)返回小于参数的最大的整数
 * public static long round(double a)四舍五入
 * public static float max(float a,float b)返回两个数的较大值
 * public static double min(double a, double b)返回两个数的较小值
 * public static double random()返回一个大于等于0.0小于1.0的随机小数
 */
public class Example{
	public static void main(String[] args) {
		System.out.println("计算绝对值后的结果:"+Math.abs(-1));
		System.out.println("求大于参数的最小整数:"+Math.ceil(5.6));
		System.out.println("求小于参数的最大的整数:"+ Math.floor(-4.2));
		System.out.println("对小数进行四舍五入后的结果:"+Math.round(-4.6));
		System.out.println("求两个数的最大值:"+ Math.max(2.1, -2.1));
		System.out.println("求两个数的最大值:"+ Math.min(2.1, -2.1));
		System.out.println("生成一个大于等于小于1.0的随机值"+Math.random());
	}
}

运行结果:

 Random类

      在JDK的java.util包中的有一个Random类,它可以在指定的取值范围内随机产生数字。在Random类中提供了两个构造方法,具体如下表所示:

 表中列举了Random类的两个构造方法,其中第一个构造方法是无参的,通过它创建的Random实例对象每次使用的种子是随机的,因此每个对象所产生的随机数不同。如果希望创建的多个Random实例对象产生相同序列的随机数,对象时调用第二个构造方法,传入相同的种子即可。

import java.util.Random;
/*
 * 使用构造方法Random()产生随机数
 * 
 */
public class Example{
	public static void main(String[] args) {
		Random r = new Random();
		//随机产生10个[0~100]之间的整数
		for(int i = 0; i< 10; i++) {
			System.out.println(r.nextInt(100));
		}
	}
}

运行结果:

import java.util.Random;
/*
 * 使用构造方法Random(long seed)产生随机数
 */
 
public class Example{
	public static void main(String[] args) {
		Random r = new Random(13);
		//随机产生10个[0~100]之间的整数
		for(int i = 0; i< 10; i++) {
			System.out.println(r.nextInt(100));
		}
	}
}

运行结果:

 

 包装类

     在Java中,很多类中的方法都需要接受引用类型的对象,此时就无法将一基本数据类型的值传入。为了解决这样的问题,JDK中提供了一系列的包装类,通过这些包装类可以将基本数据类型的值包装为引用数据类型的对象。在Java中,每种基本类型都有对应的包装类,具体如下表所示:

 表中,列举8种基本数据类型及其对应的包装类。其中,除了Integer和Character类,其他包装类的名称和基本数据类型的名称一致,只是类名的第一个字母需要大写。

包装类和基本数据类型在进行转换时,引入了装箱的拆箱的概念,其中装箱是指将基本数据类型的值转为引用数据类型,反之,拆箱是指将引用数据类型的对象转为基本数据类型。

/*
 * 装箱:装箱是指将基本数据类型的值转换为引用数据类型
 * 
 * 通过构造方法,完成装箱操作
 *    int-->Integer
 *    Integer(int n)
 */
public class Example{
	public static void main(String[] args) {
		int a = 20;
		Integer in = new Integer(a);
		System.out.println(in);
	}
}

运行结果:

/*
 * 拆箱:拆箱是指将引用数据类型的对象转为基本数据类型
 * 
 * Integer类的方法
 * public int intValue() 以int类型返回该Integer的值
 */
public class Example{
	public static void main(String[] args) {
		Integer num = new Integer(20);
		int a= 10;
		int sum = num.intValue() +a;
		System.out.println("sum="+sum);
		
	}
}

运行结果:

列举了Integer的常用方法,其中的intValue()方法可以将Integer类型的值转为int类型,这个方法可以用来进行拆箱操作。

/*
 * 通过一个案例来演示parseInt()方法的使用,该案例实现了在屏幕上打印”*“矩形,其中宽和高分别设为20和10
 * 
 * Integer类得到方法:
 * public static int parInt(String s)将字符串整数,解析成int类型
 * StringBuffer的方法:
 * public String toString() 获取字符串缓冲区的内容,以字符串形式返回
 */
public class Example{
	public static void main(String[] args) {
		int w = Integer.parseInt("20");
		int h = Integer.parseInt("10");
		for(int i = 0; i<h; i++) {//行数
			StringBuffer sb = new StringBuffer() ;
			for(int j = 0; j < w;j++) {
			sb.append("*");
			}
			System.out.println(sb.toString());
		}
	}
}

运行结果:

 案例   字符串排序程序设计

import java.util.Arrays;
/*
 * 字符串排序程序
 */
public class Example{
private static final Object[] num_arr = null;
public static void main(String args[]) {
	String numStr = "20 78 9 -7 88 36 29";
	System.out.println(numStr);
	//调用方法,实现得到一个有小到大的字符串
	numStr = sortStringNumber(numStr);
	System.out.println(numStr);
}
//返回一个到一个由小到大的字符串"-7 9 20 29 36 78 88"
public static String sortStringNumber(String numStr) {
	//1.将字符串变成字符串数组
	String[] str_arr = numStr.split(" ");
	//2.将字符串数组变成int数组
	int[] num_arr = toIntArray(str_arr);
	//3.对int数组元素排序
	Arrays.sort(num_arr);
	//4.将排序后的int数组变成String
	String temp = arrayToString(num_arr);
	return temp;
}

//将int数组转换成String
public static String arrayToString(int[] num_arr) {
	StringBuffer sb = new StringBuffer();
	//通过循环,得到每一个int元素
	for(int i =0; i<num_arr.length; i++) {
		//判断当前元素,是否为数组最后一个元素
		if(i == num_arr.length -1) {
			sb.append(num_arr[i]);
		}else {
			//不是最后一个元素
			sb.append(num_arr[i]+" ");
		}
	}
	return sb.toString();
}
//将String数组转换成int数组
public static int[] toIntArray(String[] str_arr) {
	//创建int数组
	int[] arr = new int[str_arr.length];
	//把String数组元素转换成int元素,存储到int数组中
	for(int i= 0; i<str_arr.length;i++) {
		//得到每一个字符串str_arr[i]
		//把字符串数字转换成int类型 Integer.parseInt(String str)
		arr[i] = Integer.parseInt(str_arr[i]);
	}
	return arr;
	
}
}

运行结果:

 JDK新特性——switch语句支持字符串类型

      在JDK7中,switch语句的表达式增加了对字符串类型的支持。 由于字符串的操作在编程中使用频繁,这个新特性的出现为Java编程带来了便利。

/*
 * 在JDK7中,switch语句的表达式增加了对字符串类型的支持
 */
public class Example{
	public static void main(String[] args) {
		String week = "Friday";
		switch(week) {
		case"Monday":
			System.out.println("星期一");
			break;
		case"Tuesday":
			System.out.println("星期二");
			break;
		case"Wednesday":
			System.out.println("星期三");
			break;
		case"Thursday":
			System.out.println("星期四");
			break;
		case"Friday":
			System.out.println("星期五");
			break;
		case"Sturday":
			System.out.println("星期六");
			break;
		case"Sunday":
			System.out.println("星期天");
			break;
		default:
			System.out.println("您输入有误...");
			
		}
	}
}

运行结果:

目录

第四章面向对象

异常

try...catch和finally

 throws关键字

 运行时异常和编译时异常

自定义异常

 访问控制

第五章JavaAPI类的初始化

String类和StringBuffer类的使用

 String类的常见操作

StringBuffer类

案例  记录一个子串在整串中出现的次数

 System类

 currentTimeMillis()

 arraycopy(Object src,int srcPos,Object destPos,int length)

 Runtime类

Math类

 Random类

 包装类

 案例   字符串排序程序设计

 JDK新特性——switch语句支持字符串类型


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值