slideJava的基础教程好.ppt_第1页
slideJava的基础教程好.ppt_第2页
slideJava的基础教程好.ppt_第3页
slideJava的基础教程好.ppt_第4页
slideJava的基础教程好.ppt_第5页
已阅读5页,还剩61页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1,Objectives,To use the String class to process fixed strings To use the Character class to process a single character To use the StringBuffer class to process flexible strings To learn how to pass strings to the main method from the command line To discover file properties, delete and rename files using the File class To write data to a file using the PrintWriter class To read data from a file using the Scanner class,2,Introduction(P262 8.1),String are used often in programming. A String is a sequence of characters. In many language ,strings are treated as array of characters, but in Java a string is an Object.,3,Strings Are Immutable(8.2.2),A String object is immutable; its contents cannot be changed. Does the following code change the contents of the string? String s = “Java“; s = s + “HTML“;,4,Construct a String,(1) To creating a string from a string literal (2) Since strings are used frequently, Java provides a shorthand initializer for creating a string: (3) Create a string from an array of characters,String message = new String(“Welcome to Java“);,String message = “Welcome to Java“;,char charArray = g,o,o,d; String message = new String(charArray);,5,Interned Strings,String s1 = new String(“welcome to java“); String s2 = new String(“welcome to java“); System.out.println(s1=s2);,String s1 = “welcome to java“; String s2 = “welcome to java“; System.out.println(s1=s2);,String s1 = “welcome to java“; String s2 = new String(“welcome to java“); System.out.println(s1=s2);,6,Interned Strings(8.2.2),Since strings are immutable and are frequently used, to improve efficiency and save memory, the JVM uses a unique instance for string literals with the same character sequence. Such an instance is called interned. You can also use a String objects intern method to return an interned string.,Examples(8.2.2),Display: s1 = s is false s2 = s is true s = s3 is true,A new object is created if you use the new operator. If you use the string initializer, no new object is created if the interned object is already created.,8,Finding String Length(8.2.4),Definition: public int length(),String message = “Welcome“; int length = message.length(); /7 for(int i = 0; i message.length(); i+) ,9,Retrieving Individual Character(8.2.4),Definition : public char charAt(int index),String message = “welcome to java“; char c1 = messsage.charAt(0);/w char c2 = messsage.charAt(message.length()-1);/a,10,Exercise 1,输入任意字符串,将其反向输出 Scanner input = new Scanner(System.in); String s = input.next(); 反向输出s,11,Exercise 2(P270 listing8.1),判断一个字符串是不是回文(palindrome) Palindrome:dad,mom,noon Not Palindrome:ok,event,12,Exercise 3,编写方法count,在字符串中寻找一个字符的出现次数,例如 count(“welcome”,e);/returns 2 public static int count(String str,char c) ,13,Obtaining Substrings(8.2.6),Definition: public String substring(int beginIndex) public String substring(int beginIndex, int endIndex),String s1 = “Welcome to Java“; String s2 = s1.substring(0, 11);/(0-includsive, 11-excludsive) String s3 = s1.substring(11); /11-includsive,14,Finding a Character or a Substring(8.2.8),public int indexOf(int ch) public int indexOf(String s) Returns the index of the first occurrence of the specified character/string -1 if the character does not occur public int lastIndexOf(int ch) public int lastIndexOf(String ch) Returns the index of the last occurrence of the specified character -1 if the character does not occur,15,Example,String message = “Welcome to Java”; int index = message.indexOf(a); /12. index = message.indexOf(x); /-1. index = message.indexOf(“java”); /-1. index = message.indexOf(“Java”); /11. index = message.lastIndexOf(“va”); /13.,16,Finding a Character or a Substring(8.2.8),public int indexOf(int ch, int fromIndex) public int indexOf(String s, int fromIndex) Returns the index string of the first occurrence of the specified character/string, starting the search at the specified index. -1 if the character does not occur public int lastIndexOf(int ch, int fromIndex) public int lastIndexOf(String str, int fromIndex) Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index. -1 if the character does not occur,17,Example,String message = “Welcome to Java”; int index = message.indexOf(“a“, 13);/14. index = message.indexOf(“We“, 5);/returns -1. index = message.indexOf(o, 2);/? index = message.indexOf(o, 6);/?,18,Exercise 4,编写程序,输出任意double数的整数部分几位,小数部分几位? 例如:123456.69,整数部分6位,小数部分2位 Scanner input = new Scanner(System.in); double num = input.nextDouble(); 提示: 1.将num转换为字符串:String snum = num + ”; 2.找到小数点的位置 :int point = snum.indexOf(?); 3.截取整数部分子串 : String part1 = snum.subString(?,?); 4.截取小数部分子串 :String part2 = snum.subString(?); 5.分别输出整数部分长度和小数部分长度,19,Exercise 5,输入任意文件路径,输出其路径、文件名、文件扩展名。 例如输入: E:/08-09-2-Java/PPT/chapter8.ppt 输出: 文件路径:E:/08-09-2-Java/PPT 文件名:chapter8 文件扩展名:ppt,20,Exercise 6,实现indexOf函数 public int indexOf(String s1,String s2) 在s1中找s2,返回其首次出现的位置,找不到返回-1 不使用String类的indexOf ! ,21,Exercise 7,编写函数compare,比较两个字符串从同一位置开始,有多少个字符连续相同,返回最大的相同数。 例如: “6220462” “9020466” ,4个 “622046212121” “902046612121”,5个 static int compare(String s1,String s2) ,22,String Comparisons(8.2.3),public boolean equals(Object o),Scanner input = new Scanner(System.in); String s1 = input.next(); String s2 = input.next(); if(s1.equals(s2) System.out.println(“两个字符串包含的字符相同”); ,23,思考题,class Circle double radius; Circle(double newRadius) radius = newRadius; 测试: Circle c1 = new Circle(5.5); Circle c2 = new Circle(5.5); System.out.println(c1.equals(c2);/false,24,public boolean equals(Object anObject) if (this = anObject) return true; if (anObject instanceof String) String anotherString = (String)anObject; int n = count; if (n = anotherString.count) char v1 = value; char v2 = anotherString.value; int i = offset; int j = anotherString.offset; while (n- != 0) if (v1i+ != v2j+) return false; return true; return false; ,equals是Object类中的一个方法(该方法将比较两个对象的地址是否相同),它被java所有的类继承。如果某个类对于equals条件有任何其他要求,则需要改写equals方法,下面是String类的equals方法。仿照该方法为Circle类提供equals方法,当两个圆的半径相同返回true,否则返回false。,25,String Comparisons(8.2.3),public boolean startsWith(String prefix) public boolean endsWith(String suffix),Scanner input = new Scanner(System.in); String s1 = input.next(); if(s1.startsWith(“java”) System.out.println(“该字符串由java开头”); if(s1.endsWith(“java”) System.out.println(“该字符串由java结尾”); ,26,Matching String(8.6.1),public boolean matches(String regex),Scanner input = new Scanner(System.in); String s1 = input.next(); if(s1.matches(“d.*d”) System.out.println(“该字符串由数字开头,数字结尾”); if(s1.matches(“A-Z1,40-92”) System.out.println(“该字符串1-4个A-Z字符开头,以2 个数字结尾”); ,27,“.”代表任何字符 “d”代表任何数字,“D”代表任何非数字字符 “s”代表空格,“S”代表任何非空格字符 “x*”代表0个或多个x,(xy)*代表0个或多个xy “x?”代表0个或1个x,(xy)?代表0个或1个xy “x+”代表1个或多个x,(xy)+代表1个或多个xy xyz表示取x,y,z其中一个 0-9表示取0-9其中一个 x|y|z表示取x,y,z其中一个 “x5”表示5个x “x5,”表示至少5个x “x5,8”表示至少5个x,最多8个x (xyz)2表示xyz出现两次,28,Exercise 8,判断一个字符串是不是java合法标识符,regex 代表java合法标 识符:字母(pL),下划线,$开头,后跟字母,下划线,数字pN,$任意组合 Scanner input = new Scanner(System.in); String s = input.next(); String regex = “(pL|_|$)(pN|pL|_|$)*”; if(s1.matches(regex) System.out.println(“该字符串可以作为Java标识符”); ,29,Exercise 9,判断输入是不是正确的邮件地址 正确地址: 字母(包括大小写)数字的任意组合 + + 字母(包括大小写)数字的任意组合 + .net或者.com,30,String Conversions(8.2.7),public String toUpperCase() public String toLowerCase() public String trim() public String replace(char oldChar, char newChar),Scanner input = new Scanner(System.in); String s = input.next(); String su = s.toUpperCase(); String sl = s.toLowerCase(); String st = s.trim(); String sr = s.replace(a,A);,31,Split string,String s = “12,13,15,16,18,19”; String sArray = s.split(“,”);,sArray,32,Convert Character and Numbers to Strings(8.2.10),String to number String sdnum = “12.5”; String sinum = “50”; double dnum = Double.parseDouble(snum); int inum = Integer.parseInt(sinum); Number to String double d = 14.8; String snum = d + “” ;,33,Exercise 10,输入一串用“,”分隔的数字串,求和,34,The StringBuffer Class(P273 8.4),The StringBuffer class is an alternative to the String class. In general, a string buffer can be used wherever a string is used. StringBuffer is more flexible than String. You can add, insert, or append new contents into a string buffer.,35,StringBuffer Constructors,public StringBuffer() No characters, initial capacity 16 characters. public StringBuffer(int length) No characters, initial capacity specified by the length argument. public StringBuffer(String str) Represents the same sequence of characters as the string argument. Initial capacity 16 plus the length of the string argument.,36,Appending New Contents into a String Buffer,StringBuffer strBuf = new StringBuffer(); strBuf.append(“Welcome“); strBuf.append( ); strBuf.append(“to“); strBuf.append( ); strBuf.append(“Java“);,37,insert New Contents into a String Buffer,StringBuffer mainStr = new StringBuffer(“黄河远上白云,一片孤城万仞山“); String subStr = “间“; mainStr.insert(6, subStr); System.out.println(mainStr);,38,delete Contents from a String Buffer,StringBuffer mainStr = new StringBuffer (“黄河远上白云间,一片孤城万仞山“); mainStr.deleteCharAt(4); System.out.println(mainStr); StringBuffer mainStr2 = new StringBuffer (“黄河远上白云间,一片孤城万仞山“); mainStr2.delete(0,8); System.out.println(mainStr2);/一片孤城万仞山,39,modify String Buffer,StringBuffer modiStr = new StringBuffer (“When i am young, Id listening to the radio“); modiStr.setCharAt(5, I); modiStr.replace(7, 9, “was“); System.out.println(modiStr);,40,Exercise 15,从输入的字符串中删除指定的字符串,例如:输入“this is a string”,删除“is”,删除后的串为”th a string” static String delete (String s,String del) ,41,Exercise 16,将一个十进制的字符串转换为逗号分隔的字符串,从右边开始每三个数字标一个逗号。例如1234567,返回1,234,567 static String insert(String num, int interval) ,42,The Character Class,43,Example,char c = f; if(Character.isDigit(c) System.out.println(c+“是数字“); else if(Character.isLetter(c) System.out.println(c+“是字母“); ,44,Example,char c = f; if (Character.isUpperCase(c) System.out.println(c + “是大写“); else if (Character.isLowerCase(c) System.out.println(c + “是小写“); else System.out.println(c + “不分大小写“); ,45,Example,char c = f; if (Character.isUpperCase(c) System.out.println(Character.toLowerCase(c); else if (Character.isLowerCase(c) System.out.println(Character.toUpperCase(c); else System.out.println(c + “不分大小写“); ,46,Example,char c = 1; if (Character.isDigit(c) int num = Character.getNumericValue(c); num+; System.out.println(num); else System.out.println(c + “不是数字“); ,47,Exercise 11,统计一个字符串中有多少个数字, 例如:”cat223dog456n”中数字个数是6 public static int count(String s) ,48,Exercise 12,二进制转化为10进制 public static int parseBinary(String binaryString) int num = parseBinary(“1001”): 1*23+0*22+0*21+1*20 = 9;,49,Exercise 13,统计一个字符串中每个数字出现多少次 public static int count(String s) int count = new int10; 提示:用counti存储i的个数 例如: int count = count(“12203AB3”); 输出: 0出现1次 1出现1次 2出现2次 3出现2次 4出现0次 ,50,Exercise 14,统计字符串中有多少个数字段 例如:“cat223dog456nice25ttt98” 数字段个数是4 public static int count(String s) ,51,The File Class,The File class is a wrapper class for the file name and its directory path.,52,53,import java.io.*; public class TestFileClass public static void main(String args) File file = new File(“d:/image/us.gif“); System.out.println(“Does it exist? “ + file.exists(); System.out.println(“Can it be read? “ + file.canRead(); System.out.println(“Can it be written? “ + file.canWrite(); System.out.println(“Is it a directory? “ + file.isDirectory(); System.out.println(“Is it a file? “ + file.isFile(); System.out.println(“Is it absolute? “ + file.isAbsolute(); System.out.println(“Is it hidden? “ + file.isHidden(); System.out.println(“Absolute path is “ + file.getAbsolutePath(); System.out.println(“Last modified on “ + new java.util.Date(file.lastModified(); ,54,Create File,File f1 = new File(“D:/test/a.doc”); /创建指定文件 boolean b = f1.createNewFile(); File f2 = new File(“D:test1test2“); /创建指定文件夹,如果上层文件夹不存在,会一同创建 boolean b = f2.mkdirs(); /只创建最后一层文件夹,如果上层文件夹不存在,创建失败 b = f2.mkdir();/,55,Delete file,File f1 = new File(“D:/test/a.doc”); f1.delete ();/删除文件 File f2 = new File(“D:/test“); f2.delete();/删除文件夹,文件夹必须为空才能删除,56,Rename file,将D:/test/a.doc重命名成b.doc File f1 = new File(“D:/test/a.doc“); File f2 = new File(“D:/test/b.doc“); f1.renameTo(f2); 将D:/test/a.doc转移到D:/ File f1 = new File(“D:/test/a.doc“); File f2 = new File(“D:/a.doc“); f1.renameTo(f2);,57,Writing Data Using PrintWriter,import java.io.*; public class PrintWriterDemo public static void main(String args) throws FileNotFoundException PrintWriter pw = new PrintWriter(“d:/a.txt”); pw.println(“天天好心情_“); pw.print(123456); pw.close(); ,58,Writing Data Using PrintWriter,import java.io.*; Import java.util.*; public class PrintWriterDemo public static void main(String args) throws FileNotFoundException Scanner in = new Scanner(System.in); PrintWriter pw = new PrintWriter(“d:/a.txt“); for(int i =0;i2;i+) System.out.println(“请输入学号“); String id = in.next(); pw.print(id + “ “); System.out.println(“请输入姓名“); String name = in.next(); pw.print(name + “ “); System.out.println(“请输入年龄“); int age = in.nextInt(); pw.println(age); pw.close(); ,1 张三 20 2 李四 19,59,Writing Data Using PrintWriter,60,The Scanner Class,JDK 1.5 Feature,Scanner scanner = new Scanner(System.in); String s = scanner.next(); System.out.println(s);,Input: Welcome to Java! Java is fun! Java is cool! Output: Welcome,By default,the delimiters for separating tokens in a Scanner are whiteSpaces,61,The Scanner Class,Scanner scanner = new Scanner(System.in); scann

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论