JAVA基础知识复习3

异常

在程序运行的过程中,会发现各种非正常状况。针对这种情况,在Java中引入了异常以异常类的形

式,对这些非正常情况进行封装,通过异常处理机制,对程序形式发生的各种问题进行处理

package b;

public class Example01 {
	public static void main(String[]args) {
		
		   int result=divide(4,2);//调用divide()方法//把2改成0的话0不允许做除数就会出现异常
		   System.out.println(result);
		  }
		  //下面的方法实现了两种整数相除
		  public static int divide(int x,int y){
		   int result=x/y;
		   return result;
	

	}
}

package b;

public class Example01 {
	public static void main(String[]args) {
		int result=divide(4,0);//调用divide()方法//把2改成0的话0不允许做除数就会出现异常
		   System.out.println(result);
		  }
		  //下面的方法实现了两种整数相除
		  public static int divide(int x,int y){
		   int result=x/y;
		   return result;

	}
}

throwable继承体系

throwable类是所有异常和错误的父类

throwable有两个直接类Error错误和Exception异常

Error表示,JAVA运行时产生的系统内部错误或者资源耗尽的错误是比较严重的,仅靠修改程序是

不能够恢复的,使用JAVA命令去运行一个不存在的类,就会出现错误

Exception表示,程序本身可以处理的错误,在开发JAVA程序中进行的异常处理都是针对

Exception类及其子类,Exception类的众多子类中有一个特殊的RuntimeException该类及其子类用

于表示运行时异常,除了此类,其他类都用于表示编译时异常

方法声明功能描述
String getMessage()返回此 throwable 的详细消息字符串
void printStackTrace()将此 throwable 及其追踪输出至标准错误流
void printStackTrace(PrintStream s)将此 throwable 及其追踪输出到指定的输出流

try-catah和finally

JAVA中提供了一种对异常进行处理的方式,异常捕捉通常使用try-catah语句,具体语法格式如下

try{

//程序代码块

}

catch(Exceptiontype1 e){
//对Exceptiontype1的处理

}

在try代码块中,编译可能发生异常的JAVA语句,Catch代码块中编写针对异常进行处理的代码,当

try代码块中的程序发生异常,系统会将这个异常的信息封装成一个异常对象,并将这个对象传递给

catch代码块,Catch代码块需要一个参数,指明它所能够接收的异常类型,这个参数的类型必须是

异常类或其子类

package b;

public class Example01 {
	public static void main(String[]args) {
		//下面的代码定义了一个try...catch...finally语句用于捕获异常
		  try {
		   
		   int result=divide(4,2);//调用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;

	}
}

package b;

public class Example01 {
	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关键字对外声明,该方法有可能发生的异常,这样,调用者

在调用方法时就明确的知道该方法有异常,并且必须在程序中对异常进行处理,否则编译无法通

throwable类的常用方法

方法声明功能描述
String getMessage()返回此 throwable 的详细消息字符串
void printStackTrace()将此 throwable 及其追踪输出至标准错误流
void printStackTrace(PrintStream s)将此 throwable 及其追踪输出到指定的输出流

throws关键字需要写在方法声明的后面,throws后面需要声明方法中发生异常的类型,通常将

这种做法称为方法声明抛出一个异常

package b;

public class Example01 {
	public static void main(String[]args) {
		//下面的代码定义了一个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;

	}
}

运行时异常

在实际开发中,经常会在程序编译时产生一些异常,而这些异常必须要进行处理,这种异常被称为

编译时异常,也称为checked异常还有另一种异常是在程序运行时产生的,这种异常即使不编译异

常处理代码,依然可以通过编译,因此被称为运行时异常也称为unchecked异常。

编译时异常

异常类除了Runtimeexception类及其子类都是编译时异常,编译时异常的特点是JAVA编译器会对

其进行检查,如果出现异常,就必须对异常进行处理,否则程序无法通过编译处理,编译时期的异

常有两种方式

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

运行时异常

Runtimeexception类及其子类都是运行时异常,运行时异常的特点是JAVA编译器不会对其进行检

查,也就是说当程序中出现这类异常时,即使没有使用try-catah语句捕获或使用throws关键字声明

抛出程序也能编译通过运行时异常,一般是由程序中的逻辑错误引起的,在程序运行时无法恢复

自定义异常

JDK中定义了大量的异常类,虽然这些异常类可以描述编程时出现的大部分异常情况,但是在程序

开发中有时可能需要描述程序中特有的异常情况,为了解决这个问题,在JAVA中允许用户自定义

异常,但自定义异常类必须继承Exception类或者其子类

在实际开发中,如果没有特殊的要求,自定义的异常类只需要继承Exception类,在构造方法中使

用super()语句调用Exception构造方法即可

既然自定义了异常,我们要使用它,就需要用到throws关键字,throws关键字用于在方法中声明抛

出异常的实例对象,其语法格式如下

throws  exception 异常对象;

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>default>protected>public

private(类访问级别)

如果类的成员被private访问控制符来修饰则这个成员只能被该类的其他成员访问,其他类无法直接

访问类的良好封装就是通过private关键字来实现的

default(包访问级别)

如果一个类或者类的成员不使用任何访问控制符修饰则称它为默认访问控制级别,这个类或者类的

成员只能被本包中的其他类访问

protected(子类访问级别)

如果一个类的成员被protected访问控制符修饰,那么,这个成员既能被同一包下的其他类访问,

也能被不同包下该类的子类访问

Public(公共访问级别)

这是一个最宽松的访问控制级别,如果一个类或者类的成员被public访问控制符修饰那么这个类或

者类的成员能被所有的类访问不管访问类以被访问类是否在同一包中

类的初始化

API指的是应用程序,编程接口

在操作string类之前,首先需要对string类进行初始化,在JAVA中可以通过以下两种方式对string类

进行初始化

1、使用字符串常量直接初始化一个string对象

String  str1="abc";

2、使用string的构造方法初始化,字符串对象string的构造方法

String()                         创建一个内容为空的字符串

String(String value)      根据指定的字符串内容创建对象

String(char[ ] value)     根据指定的字符串数组创建对象

package b;

public class Example01 {
	public static void main(String[]args) {
		String str1="abc";
		//字符串常量直接赋值
		String str2=new String();
		//String()空参数构造方法,创建一个String类对象,内容为空
		String str3=new String("abcd");
		//String(String s)创建一个String类对象,指定一个字符串内容
		char[]charArray=new char[] {'E','F','G'};
		String str4=new String(charArray);
		
		
		
		System.out.println(str1);
		System.out.println("a"+str2+"b");//ab
		System.out.println(str3);
		System.out.println(str4);
	}
}

 String类的常见操作

String类在实际开发中的应用非常广泛,因此灵活的使用string类是非常重要的,String类的常用方法如下:

package W;
/*
 * 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 Exampel {
 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"));
 }

}

package W;

public class Example3 {
 /*
  * 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(" ",""));
 }

}

 

//判断字符串是否以指定的字符串开始与结束,是否包含指定字符串是否为空等
package W;
/*
 * 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 Example4 {

 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类的replace()和trim

()方法,进行字符串的替换和去除空格操作

操作字符串时,经常需要对字符串进行一些判断,如判断字符串是否以指定的字符串开始结束,是

否包含指定的字符串,字符串是否为空等

String字符串在获取某个字符时,会用到字符的索引,当访问字符串中的字符时,如果字符的索引

不存在,则会发生字符串角标越界异常

package W;
/*
 * String类的转换操作
 * 在程序开发中,经常需要对字符串进行转换操作,例如将字符串转换成数组的形式,将字符串的进行大小写转换等
 * public char[]tochatArray()将此字符串转换成字符数组
 * public static String valueof(int n)将指定int值转换成String类型
 * public String touppercase() 将此字符串中的字符全部转换成大写字母,会返回一个新的字符串
 */
public class Exampe {
 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());
  }
 }

 

//字符串的截取和分割操作
package W;
/*
 * String类的截取与分割操作
 * 在String类中针对字符串的截取和分割操作提供了两个方法
 * 其中,substring()方法用于截取字符串的一部分
 * split()方法可以将字符串按照某个字符进行分割
 * public String substring(int start)返回一个新字符串,它从原有字符串指定位置开始截取,到字符串末尾结束
 * public String substring(intstart, int end) 返回一个新字符串,它从原有字符串指定位置开始截取,到指定位置结束
 * public String[] split(String regex)按照指定的字符串进行分割返回一个字符串数组
 * 
 */
public class Example5 {
 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] +","); 
 }
  }
 }
}

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

 

String buffer类

由于字符串是常量,因此一旦创建,其内容和长度是不可改变的,如果需要对一个字符串进行修

改,则只能创建新的字符串,为了便于对字符串进行修改,在jdk中提供了一个string buffer类,也

称字符串缓冲区,string bufferLay和string类最大的区别在于它的内容和长度都是可以改变的,

string buffer类似一个字符容器当在其中,添加或删除字符时,并不会产生新的string buff类对象

针对添加和删除字符的操作,string buffer提供了一系列的方法

package b;

public class Example01 {
	public static void main(String[]args) {
		/*
		 * 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()字符串缓冲区数据翻转方法
		 */
		
				 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());
			
	}
}

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

package b;

public class Example01 {
	public static void main(String[]args) {
		/*
		 * 记录一个子串在整串中出现的次数
		 * 思路:
		 *  1.定义一个整串,定义一个子串
		 *  2.获取子串在整串中出现的次数
		 */
		
		  //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.out.println()语句,这句代码中就实用了system类,system类定义了一些系统相关的属性和

方法,它所提供的属性和方法都是静态的,因此想要引用这些属性和方法直接使用system类调用

即可

system类常见方法如下:

package b;
import java.util.Properties;
import java.util.Set;
/*
 * System类的方法
 * public static Properties getProperties()
 * 方法用于获取当前系统的全部属性,该方法会返回一个Properties类型的容器
 * 其中封装了系统的所有属性,这些属性是以”属性名=属性值“的形式存在的
 * public static String getProperty(String key)
 *  获取指定键(属性名)所对应的系统属性值
 */
public class Example01 {
	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分零秒

之间的时间差单位是毫秒,通常也将该值称为时间数

package b;

public class Example01 {
	public static void main(String[]args) {
	
		
		/*第二个:
			 * public static long currentTimeMillis()
			 * 方法返回一个long类型的值,该值表示当前时间与1970年1月1日0点0分0秒之间的时间差,单位是毫秒,通常也将该值称作时间戳
			 */
			
			  //计算程序在进行求和操作时所消耗的时间
			  
			  //计算程序在进行求和操作时所消耗的事件
			  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()

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

Src表示,源数组

Dest表示目标数组

Src POS表示,源数组中拷贝元素的起始位置

Dest pos表示,拷贝到目标数组的起始位置

Length表示,拷贝元素的个数

package b;

public class Example01 {
	public static void main(String[]args) {
	
		
		/*
   *  arraycopy(Object src,int srcPos,Object dest,int destpos,int length)
   *  arraycopy()方法用于将一个数组中的元素快速拷贝到另一个数组。其中的参数具体作用如下:
   *  src:表示源数组。
   *dest:表示目标数组。
   *srcPos:表示源数组中拷贝元素的起始位置destPos:表示拷贝到目标数组的起始位置
   *lenqth: 表示拷贝元素的个数。
   */
  
  
    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类封装了虚拟机进程,因此在程序中通常会通过该类的实例对象来获取当前虚拟机的

相关信息

package b;

public class Example01 {
	public static void main(String[]args) {
	
		 /*
		   * Runtime类的使用
		   * public int availableProcessors()想Java虚拟机返回可以处理器的数目
		   * public long freeMemory()返回Java虚拟机中的空闲内存里
		   * public long maxMemory()返回Java虚拟机试图使用的最大内存量
		   * public static Runtime getRuntime()返回与当前Java应用程序相关的运行时对象
		   */
		 
		    //获取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命令,同样的效果

 /*
   * Runtime类中提供了一个exec()方法,该方法用于执行一个dos命令,从而实现和在命令行窗口中输入dos命令同样的效果
   */ 
  import java.io.IOException;
  public class Test2{
   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 Test2{
 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

package b;

public class Example01 {
	public static void main(String[]args) {
	
		/*
		 * 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的随机小数
		 */
		
		  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类提供两个构造

方法,具体如下表所示、

方法声明功能描述
Rundom()构造方法,用于创建一个伪随机数生成器
Rundom(long seed)

构造方法,使用一个long型的seed种子创建伪随机数生成器

表中列举了Random类的两个构造方法,其中第一个构造方法是无参的

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

通过它创建Random实例对象每次使用的种子是随机的,因此,每个对象所产生的随机数不同,

相较于Math的Random法而言,Random类提供了更多的方法来生成各种伪随机数不仅可以生产整

数类型的随机数,还可以生成浮点类型的随机数表中列举了Random类中的常用方法

方法声明                                       功能描述
booleam nextBooleam()                随机生成booleam类型的随机数
double nextDouble()                     随机生成double类型的随机数
float nexFloat(()                            随机生成float类型的随机数
int nextInt()                                 随机生成int类型的随机数
int nextInt(int n)                           随机生成0~n之间的int类型的随机数
long nextLong()                              随机生成long类型的随机数

表中,列出了Random类常用的方法,其中,Random类的nextDouble()方法返回的是0.0和1.0之间double类型的值,nextFloat()方法返回的是0.0和1.0之间float类型的值,nextint(int n)返回的是0和指定值n之间的值
 

package b;

import java.util.Random;

public class Example01 {
	public static void main(String[]args) {
	
		/*
		 * Random类中的常用方法
		 * public float nexFloat()随机生成0.0 -1.0之间的float小数
		 * public double nextDouble()随机生成0.0 -1.0之间的double小数
		 */
		
				Random r1=new Random();
				System.out.println("产生float类型随机数"+r1.nextFloat());
				System.out.println("产生0-100之间int类型随机数"+r1.nextInt(100));
		
		}
	}

包装类

在JAVA中,很多类的方法都需要接收引用类型的对象,此时就无法将一个基本数据类型的值传

入,为了解决这样的问题,jdk中提供了一系列的包装类,通过这些包装类,可以将基本数据类型

的值包装为引用数据类的对象,在JAVA中,每种基本类型都有对应的包装类,具体如下表

除了Integer和Character类,其他包装类的名称和基本数据类型的名称一致,只是类名的第一个字

母需要大写包装类和基本数据类型,在进行转换时,为了引入装箱和拆箱的概念,其中,装箱是指

将基本数据类型的值转为引用数据类型,反之,拆箱是指将引用数据类型的对象转为基本数据类

package b;



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

package b;



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

Integer类除了具有object类的所有方法外,还有一些特有的方法如下表所示

其中,intvalue()方法可以将integer类型的值转为int类型,这个方法可以用来进行拆箱操作

package b;



public class Example01 {
	public static void main(String[]args) {
		/*
		 * 通过一个案例来演示parseInt()方法的使用,该案例实现了在屏幕上打印”*“矩形,其中宽和高分别设为20和10
		 * 
		 * Integer类得到方法:
		 * public static int parInt(String s)将字符串整数,解析成int类型
		 * StringBuffer的方法:
		 * public String toString() 获取字符串缓冲区的内容,以字符串形式返回
		 */
		
		  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());
		 
		}
		  
		
		 
		}
	}

案例:字符串排序设计

package b;

import java.util.Arrays;

public class Example01 {
	public static void main(String[]args) {
		 /*
		  * 字符串排序程序
		  */
		 
		
		 final Object[] num_arr = null;
		
		  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;
		  
		
		  
		
		 
		}
	}

Swith语句支持字符串类型 

在jdk 7中Switch语句的表达式增加了对字符串类型的知识,由于字符串的操作在编程中使用频繁这个新特性的出现为JAVA编程带来的便利 

package b;



public class Example01 {
	public static void main(String[]args) {
		/*
		 * 在JDK7中,switch语句的表达式增加了对字符串类型的支持
		 */
		
		  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("您输入有误...");
		 
		}
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值