440 likes | 565 Views
3.7 Java 的工具类. 3.7.1 数组. 7.1.1 声明数组 格式:数组元素类型 数组名字 [ ] 数组元素类型 [ ] 数组名字; 二维数组: 数组元素类型 数组名字 [ ][ ] 数组元素类型 [ ][ ] 数组名字;. 例如: float boy[]; double gitl[] char cat[] float a[] double[] b; 也可用定义的类来声明数组: Point line[ ];. 7.1.2 创建数组. 数组声明后,要用 new 运算符为其分配内存空间 分配内存空间时必须指明数组的长度
E N D
3.7.1数组 • 7.1.1声明数组 • 格式:数组元素类型 数组名字[ ] • 数组元素类型[ ] 数组名字; • 二维数组: • 数组元素类型 数组名字[ ][ ] • 数组元素类型[ ][ ] 数组名字;
例如: • float boy[]; • double gitl[] • char cat[] • float a[] • double[] b; • 也可用定义的类来声明数组: • Point line[ ];
7.1.2创建数组 • 数组声明后,要用new 运算符为其分配内存空间 • 分配内存空间时必须指明数组的长度 • 格式如下: • 数组名字=new 数组元素类型[个数] • 如:boy=new float[5]; • int[] age=new int[10];
声明数组时内存情况: • float boy[]; boy 0x785ba
创建数组后,内存情况: boy=new float[5]; boy 0x785ba boy[0] boy[1] boy[2] boy[3] boy[4] →
7.1.3数组元素的使用 • 数组元素的使用是通过下标实现的 • Java的数组下标由0开始 • 例:boy[0]=100f; • boy[4]=500f; • 1。数组初始化 • float boy[ ]={100f,200f,300f,400f,500f}
7.1.3数组元素的使用 • 2。拷贝数组 • 当把一个数组变量拷贝给另一个变量时,两个变量都指向相同的数组 • Float girl[]=boy; girl boy
7.1.3数组元素的使用 • 如果只是想把一个数组中的值拷贝给另一个变量,可用arraycopy方法。 • 格式: • System.arraycopy( • from,fromIndex,to,toIndex,count);
7.1.3数组元素的使用 • 例:int small[]={2,3,4,5,6,7}; • int big[]={9,8,7,6,5,4,3,2,1}; • System.arraycopy(small,1,big,0,3); • 输出big的值为: • 3,4,5,6,5,4,3,2,1
7.1.3数组元素的使用 • 3。排序 • 调用Java.util.Arrays类中的 sort方法,可对一个数组中的数字进行排序 • Static void sort(数组); • 例:Array.sort(boy); • 实例:模拟抽彩游戏LotteryDrawing.java
public class LotteryDrawing { public static void main(String[] args) { String input = JOptionPane.showInputDialog ("How many numbers do you need to draw?"); int k = Integer.parseInt(input); input = JOptionPane.showInputDialog ("What is the highest number you can draw?"); 输入数据 int n = Integer.parseInt(input); 确定为n取K
// numbers 用来存放 1 2 3 . . . n int[] numbers = new int[n]; for (int i = 0; i < numbers.length; i++) numbers[i] = i + 1; // result用不存放选取出的数 int[] result = new int[k]; for (int i = 0; i < result.length; i++) { // 在0---N-1之间产生选取出的数 int r = (int)(Math.random() * n);
// 将选出的数放入result result[i] = numbers[r]; // move the last element into the random location numbers[r] = numbers[n - 1]; n--; } // 将result排序输出 Arrays.sort(result); System.out.println ("Bet the following combination. It'll make you rich!"); for (int i = 0; i < result.length; i++) System.out.println(result[i]); System.exit(0); }}
7.1.3数组元素的使用 • 4.命令行参数 • 每个Java应用程序都有一个带String[] args参数的main方法。 • 这个参数用来接收命令行上的参数 • 例:public class Message • { public static void main(String [] args) • {
If (args[0].equals(“-h”)) • System.out.print(“Hello”); • Else if(args[0].equals(“-g”); • System.out.print(“goodbye,”); • For(int I=1;I<args.length;I++) • System.out.print(““+args[I]); • System.out.println(“!”); • } • }
如果程序用如下方法调用java Message –g cruel word • 则args数组内容如下: • 程序运行结果:goodbye,cruel world! Args参数从命令行第三个参数开始取值 Args[0]: “-g” Args[1]: “Cruel” Args[2]: “World”
3.7.2 字符串 • 本节主要内容 • 创建并使用String对象 • 学习使用String类的属性及其文方法 • 在字符串中查找子字符串 • 在字符串中提取子字符串 • 在字符串中替换子字符串
3.7.2字符串 • 一。声明 • Java基本类型中没有字符串类型 • 用String类来创建一个字符串变量,因此字符串变量是一个类类型变量,即是一个对象 • 字符串常量:“123.45”,“你好”,“hello!” • 声明字符串对象:String s;
3.7.2字符串 • 二。创建字符串: • 可以用String类的构造方法: • String(字符串常量)来构造字符串 • 如:s=new String(“I am a teacher1”); I am a Teacher.
3.7.2字符串 • 三。常用操作 • 1。串连接(+) • 例:String s1=“Hello!”; • String s2=“World”; • String s3=s1+s2; Hello! world
查看应用程序中的HTML private String htmlText = "<HTML><BODY><TABLE>" + "<TR><TD>IBM 笔记本电脑</TD>" + "<TD>€2035.67</TD></TR>" + "<TR><TD>Sony T9数码相机</TD>" + "<TD>€641.55</TD></TR>" + “<TR><TD>ARCHOS 爱可视 MP4</TD>" + "<TD>€1201.83</TD></TR>" + "</TABLE></BODY></HTML>";
获取字符串的长度 • 使用String 类中的length()方法可以获取一个字符串的长度 • String s=“I am a teacher”; • String tom=“我是老师” • int n1,n2; • n1=s.length();n2=tom.length(); • 则:n1=14,n2=4
字符串检索 • 可以用String类中的方法: • indexOf(string s) • indexOf(String s,int startpoint) • 例:String me=“I am a teacher”; • tom.indexOf(“a”);//结果为2 • tom.indexOf(“w”,3);//结果为-1
定位所选物品的名称、价格 // search for location of item and price String selectedItem = ( String ) itemJComboBox.getSelectedItem(); int itemLocation = htmlText.indexOf( selectedItem ); int priceBegin = htmlText.indexOf( "€", itemLocation ); int priceEnd = htmlText.indexOf( "</TD>", priceBegin );
获得字符串的子串 • 格式: • substring(int startpoint); • substring(int start,int end) • String jerry="I love tom”; • s1=jerry.substring(2); • s2=jerry.substring(2,5)
提取价格 // store price found in double price String priceText = htmlText.substring( priceBegin + 6, priceEnd ); double price = Double.parseDouble( priceText );
字符串与数值的转化 • java.lang包中的Integer类、Long类、Float类、Double类分别提供了相应的方法用来进行字符串与数值间的转换 • 转化为整形 • Integer.parseInt(字符串) • 例: Integer.parseInt(“12345”) • 再如:long x;String s=“1000”; • x= Integer.parseLong(s);
转化为float的double型 • 格式: • Float.valueOf(String s).floatValue(); • Double.valueOf(String s).doubleValue(); • 例:float x; double y; • String s=“23.45”; • x=Float.valueOf(s).floatValue(); • y=Double.valueOf(s).doubleValue();
数值转化为字符 • 使用String类中定义的valueOf()方法,便可将一个数值 转换为字符串 • 如: • float x=123.45f; • String s; • s=String.valueOf(x);
转化为人民币 // convert price from euros to RMB double conversionRate = Double.parseDouble( rateJTextField.getText() ); price *= conversionRate;
获得对象的字符串表示 • 所有的类都默认为java.lang包中Object类的子类或间接子类----同族同宗 • 所有的类都可以享用一些基本功能 • Object类有一个方法:toString(),可用于获得对象的字符串表示 • 例:Button button=new Button(“确定”); • System.out.println(button.tostring()); • 例:ScreenScraping.java
练习: 假若 alphabet=“abcdefghijklmnopqrstuvwxyz” alphabet. subString. (6,10)= ghit alphabet. subString. (9,16)= 7 alphabet. subString(14,14) 和 alphabet. subString (4, 4)的结果相同吗? alphabet. subString. (26,26)会失败,为什么?
7.3 数组列表 数组列表是可以动态延伸的类数组对象 数组列表无类型,它可以存放所有Object类型 从数组列表中取出的数据项,都必须进行造型转换 ArrayList类是一个库类,定义在java.util包中
一、定义 • ArrayList 对象=new ArrayList(); • 例:ArrayList staff=new ArrayList(); • API:java.util.ArrayList • ArrayList()构造一个空数组列表 • ArrayList(int c)构造一个具有指定容 量的空数组列表
二、添加新元素 • API:boolean add(Object obj) • 把元素obj追加到数组列表的结尾 • 例:staff.add(new employee(…)); • 三、统计个数 • API:int size() 返回数组列表中当前元素个数 • 例:staff.size(); • 四、调整大小 • 把数组列表的存贮空间调整到当前大小 • API:void trimtosize() 使用trimtosize() 后,再增加新元素会重新移动内存
数组列表是无类型的,每次导出对象时,都要作造型转换数组列表是无类型的,每次导出对象时,都要作造型转换 • 五、访问 • API:void set(int index,Object obj) • 将obj放入数组列表index位置 • Object get(int index) • 获得指定位置index的元素值 • 例:Employee harry=newEmployee(…); • staff.set(5,harry); • Employee e=(Employee)staff.get(5);
六、增加与删除 • boolean add(int n,Object obj) • 在第n 个位置插入obj • Object remove(n); • 将第n个位置存放的对象删除 • 例:staff.add(5,harry); • Employee • e=(Employee)staff.remove(5); • 例:ArrayListTest.java
import java.util.*; public class ArrayListTest { public static void main(String[] args) { ArrayList staff = new ArrayList(); staff.add(new Employee("Carl Cracker", 75000, 1987, 12, 15)); staff.add(new Employee("Harry Hacker", 50000, 1989, 10, 1)); staff.add(new Employee("Tony Tester", 40000, 1990, 3, 15));
// raise everyone's salary by 5% for (int i = 0; i < staff.size(); i++) { Employee e = (Employee)staff.get(i); e.raiseSalary(5); } // print out information about all Employee objects for (int i = 0; i < staff.size(); i++) { Employee e = (Employee)staff.get(i); System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay=" + e.getHireDay()); } } } // raise everyone's salary by 5% for (int i = 0; i < staff.size(); i++) { Employee e = (Employee)staff.get(i); e.raiseSalary(5); } // print out information about all Employee objects for (int i = 0; i < staff.size(); i++) { Employee e = (Employee)staff.get(i); System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay=" + e.getHireDay()); } } }//class ArrayListTest ended
class Employee { public Employee(String n, double s, int year, int month, int day) { name = n; salary = s; GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day); // GregorianCalendar uses 0 for January hireDay = calendar.getTime(); }
public String getName() { return name; } public double getSalary() { return salary; } public Date getHireDay() { return hireDay; }
public void raiseSalary(double byPercent) { double raise = salary * byPercent / 100; salary += raise; } private String name; private double salary; private Date hireDay; }//end of Employee