Arrays , Collections , Scanner , Runtime

来源:互联网 发布:sql注入攻击实验 编辑:程序博客网 时间:2024/05/04 15:36


增强for循环:用于遍历,不能排序。

/*  增强for循环 for(集合或者数组中元素的数据类型 变量名 : 数组或Collection集合名) { 执行语句; }  */class StrongForDemo{public static void main(String[] args){    int[] a = {1,2,3,4,5};//普通遍历方法for (int x=0;x<a.length ;x++ ){System.out.println(a[x]);}System.out.println("********************** ");for(int x:a){    //int为数值类型 x是变量 a是数组或者集合名      System.out.println(x);}}}


collections是集合的一个工具类,提供了一系列静态方法。

collections常用方法:

public class CollectionsDemo {public static void main(String[] args) {ArrayList<String> array = new ArrayList<String>();array.add("haha");array.add("hehe");array.add("xixi");array.add("gaga");// 测最大最小值  max:最大  min:最小String s = Collections.max(array);//最大值String s = Collections.min(array);//最小值System.out.println(s);// 排序  直接给数组或者集合进行排序    sort:排序Collections.sort(array);// 折半查找  binarySearch:折半int index = Collections.binarySearch(array, "xixi");// 反转  reverser:反转Collections.reverse(array);}}

Arrays常用方法:

toString:把数组转换成字符串返回。


计算时间的方法:

//static long currentTimeMillis() :返回以毫秒为单位的当前时间。public class SystemTest {public static void main(String[] args) {long start = System.currentTimeMillis();//将程序开始的时间赋值给startfor (int i = 0; i <10000; i++) { //for循环遍历1-10000System.out.println(i);}long end= System.currentTimeMillis();//将程序结束的时间赋予endlong time= end -start; //记录程序运行的时间System.out.println("总共用时:"+time+"毫秒");}}

Runtime类:

import java.io.IOException;/**Runtime:单例设计模式的应用。**public static Runtime getRuntime() **功能:可以执行path路径中配置过的exe文件。**/public class exectest {public static void main(String[] args) {//获取Runtime的对象  RuntimeRuntime rt=Runtime.getRuntime();//获取单例模式返回的Runtime类对象try {rt.exec("notepad"); //调用exec方法运行记事本} catch (IOException e) {e.printStackTrace();}}}

Scanner数据录入:

/* * Scanner:如果Scanner接受数据的时候,如果不匹配,那么Scanner对象本身就失效。也就是对象不能在被使用。 * * 创建对象:Scanner sc = new Scanner(System.in); * 使用功能:String nextLine() *  int nexeInt() */public class ScannerDemo1 {public static void main(String[] args) {System.out.println("请输入数据:");while(true){Scanner sc = new Scanner(System.in);//每一次循环进来都是新建一个对象try{                   int num = sc.nextInt();//建立参数接受要输入的值System.out.println(num);//输出你打印的值if(num == 20)//如果输入的值等于20break; //程序跳出}catch (InputMismatchException im){ //抓捕异常并处理System.out.println("输入数据类型错误");//输出异常//sc =new Scanner(System.in);//throw new RuntimeException("输出数据类型错误");//抛异常给JVM,程序终止}  }   }}


原创粉丝点击