課件南大面試lecture5 2012_第1頁
課件南大面試lecture5 2012_第2頁
課件南大面試lecture5 2012_第3頁
課件南大面試lecture5 2012_第4頁
課件南大面試lecture5 2012_第5頁
已閱讀5頁,還剩61頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

Stringclass/CharacterStringBuffer/FileIntroductiontoAstringisaseriesofcharacterstreatedasasingleConstructingStringnewString=newStringmessage=newString("WelcometoJavaprovidesashorthandinitializerforcreatingaStringmessage="WelcometoString:forstringconstantsStringBuffer/StringBuilder:forstringvariablesIntroductionIntroductiontoJavacharchararray[]={?b?,?i?,?r?,?t?,?h?,??,?d?,?a?,bytebytearray[]={?n?,?e?,?w?,??,?y?,?e?,?a?,?r?};StringBufferbuffer;Strings,s1,s2,s3,s4,s5,s6,s7;publicvoidinit(){s=newString(“hello”);buffer=newStringBuffer();s1=new //anulls2=new //s3=newString(chararray); s4=newString(chararray,6,3); s5=newString(bytearray,0,4,4);//s6=newString(bytearray, //news7=new // StringsAreAStringobjectisimmutable;itscontentscannotbeStrings=s=AfterStrings=

After s=

:StringobjectforIntroductionIntroductiontoJavaStringobjectfors:Stringobjectfors:

Thisstringobjectisnowunreferenced

s:Stringobjectfors1==s1==sisfalses2==sistrues==s3istrueIntroductiontoJavacanonical Strings="WelcometoStrings1=newString("WelcometoJava");Strings2=ern();Strings3="WelcometoSystem.out.println("s1==sis"+(s1==s));System.out.println("s2==sis"+(s2==s));System.out.println("s==s3is"+(s==

::for"Welcometo:AstringobjectforRetrievingIndividualCharactersinapubliccharcharAt(int selectandreturnthecharataspecificposition(index:0..length-1)inthestring“welcometoJava”.charAt(0)(returns

12 WelcometoJaWelcometoJavaStringpublicStringconcat(String s1.concat(s2)concatenatess1ands2asanewobjecttobereturned,ands1ands2arenotIfs2.length==0thenreturntheoriginal==s1+s1+s2+s3+s4+s5sameasmessage.substring(0,message.substring(0,IntroductiontoJavasubstring:enabletocreateanewstringbycopingpartofanexistingobject(s)publicStringsubstring(intbeginIndex,intendIndex):returnasubstringcopyofthecharactersfrombeginIndextoendIndex-1.Strings1="WelcometoStrings2=s1.substring(0,11)+ 12 ComparingStringsLexicographicalcomparison:theintegerUnicodevaluesthatrepresenteachcharacterineachstringarecomparedpublicbooleanequals(Objects1.equals(s2)returnstrueIFs2isastringandhasthesamelengthandthesameUnicodecharactersasthecurrentstring(s1),otherwisereturnsfalse andprimitivedatatypes: bothprimitivedatatypevaluesareidentical/bothreferencesrefertothesameobjectinmemoryComparingStringspublicbooleanequalsIgnoreCase(StringIfthecaseoflettersisignored,twocharacters(c1,c2)areequalonlywhen:(a)c1==c2; publicintcompareTo(String0anegatives1islessthanapositives1isgreaterthanThereturnvalueisthedifferencebetweentheinteger example,h(104)-H(72)=ComparingStringspublicboolean(intstart,Strings2,intostart,int (booleanignCase,intstart,Strings2,intostart,intStringStringstr="Look,booleanb1,b2,b1=str.regionMatches(6,"Look",0, //b2=str.regionMatches(true,6,"Look",0,4);b3=str.regionMatches(true,6,"Look",0,5);publicbooleanstartsWith(Stringprefix,intpublicbooleanstartsWith(StringStringThecontentsofastringcannotbechangedoncethestringiscreated.Butyoucanconvertastringtoanewstringusingthefollowingmethods:FindingaCharacteroraSubstringinaindexOf:searchthefirstoccurrenceofacharacter/substringinastring(s)publicintindexOf(charch,intlastIndexOf:searchthelastoccurrenceofacharacter/substringinastring(s)publicintlastIndexOf(Stringstr,intJava".indexOf('W')returnsJava".indexOf('x')returns-Java".indexOf('o',5)returnsJava".indexOf("come")returnsJava".indexOf("Java",5)returnsJava".indexOf("java",5)returns-"WelcometoJava".lastIndexOf('a')returnsIntroductiontoJavaConversionIntroductiontoJavapublicchar[]s.toCharArray();createsanewcharacterarraycontainingacopyofthecharactersinsExample removeallappearancesofthecharacterinthePublicstaticStringsqueezeOut(Stringfrom,char{char[]chars=from.toCharArray();intlen=chars.length;for(inti=0;i<len;i++) if(chars[i]==toss){System.arraycopy(chars,i+1,chars,i,len--i; returnnewString(chars,0, IntroductiontoJavaConvertCharacterIntroductiontoJavaTheStringclassprovidesseveralstaticvalueOf()methodsforconvertingacharacter,anarrayofcharacters,andnumericvaluestostringsThesemethodshavethesamenamevalueOf()withdifferentargumenttypeschar,char[],double,long,int,andfloatForexample,toconvertadoublevaluetoastring,useString.valueOf(5.44).ThereturnvalueisstringIntroductiontoJavaIntroductiontoJavaObjective:Checkingwhetherastringisapalindrome:astringthatreadsthesameforwardandbackward publicstaticbooleanisPalindrome(String{//Theindexofthefirstcharacterintheintlow=//Theindexofthelastcharacterintheinthigh=s.length()-1;while(low<high){if(s.charAt(low)!=s.charAt(high))returnfalse;//Notapalindromehigh--;}returntrue;//ThestringisapalindromeWrapper

Noclassforbyteand[NumberType]MIN_VALUE,MAX_VALUE[Float,Doble]NEGATIVE_INFINITY,POSITIVE_INFINITYNaN(aninvalidfloatTheCharacter+Character(value:+charValue():+compareTo(anotherCharacter:Character):+equals(anotherCharacter:Character):+isDigit(ch:char):+isLetter(ch:char):+isLetterOrDigit(ch:char):+isLowerCase(ch:char):+isUpperCase(ch:char):+toLowerCase(ch:char):+toUpperCase(ch:char):

ConstructsacharacterobjectwithcharvalueReturnstrueifthischaracterequalstoanotherReturnstrueifthecharacterisanuppercaseletterCharactercharObject=newcharOpareTo(newCharacter('a'))//1charOpareTo(newCharacter('b'))//0charOpareTo(newCharacter('c'))//-1charOpareTo(newCharacter('d')//–2IntroductiontoJavaIntroductiontoJavaObjective:Counteachletterinastringignoringcase-sensitive //InvokethecountLettersmethodtocounteachint[]counts=…/**Counteachletterinthestringpublicstaticint[]countLetters(Strings){int[]counts=newint[26];for(inti=0;i<s.length();{if(Character.isLetter(s.charAt(i)))counts[s.charAt(i)-'a']++;}return}ObjectsoftheStringclass:read-StringBuffer/StringBuilder:modifiable,andusedtoimplement+and+=StringBuffervs.StringBuilderpublicCreateanullstring(theinitialcapacityofcharsispublicStringBuffer(intCreateanullbuffer,wherelengthistheNegativeArraySizeException,IfpublicStringBuffer(StringCreateabuffercontainingthecharactersofstr,andaninitialcapacitywhichisLengthandpublicintThenumberofcharacterscurrentlyinthepublicintThenumberofcharacterscanbestoredinthepublicvoidsetLength(intincrease/decreasethelengthofapublicvoidensureCapacity(intEnsurethecapacitytoaminimumofminCapacityStringBuffersmaybeautomaticallyextendedwhencharactersareappended.ButitisnotsoCapacitymethodsmaybeusedtoavoidextendingbuffersformany10overloadedappendmethods,allowingvariousdatatypevaluestobeaddedtotheendofastringbuffer,example:publicStringBufferappend(doublepublicStringBufferappend(ObjectpublicStringBufferappend(charstr[],intoffset,intpublicStringBufferappend(StringActually,StringBufferandappendareusedbycompilertoimplement+and+=forconcatenating”BC”+22isperformedasIntroductionIntroductiontoJava9overloadedinsertmethods,allowingvariousdatatypevaluestobeinsertedatanypositioninastringpublicStringBufferinsert(intoffset,booleanpublicStringBufferinsert(intoffset,charStringBufferbuf=newStringBuffer();Stringnow=newjava.util.Date().toString();buf.ensureCapacity(buf.length()+now.length()+2);buf.insert(0,now).insert(now.length(),":");IntroductionIntroductiontoJavaPublicstaticStringBufferremove(StringBufferbuf,intpos,intcnt){if(pos<0||cnt<0||pos+cnt>buf.length())thrownewintleftover==buf.length()–(pos+cnt)if(leftover==0){buf.setLength(pos);returnbuf;}char[]chrs=newchar[leftover];buf.getChars(pos+cnt,buf.length(),chrs,0);returnbuf;}IntroductiontoJavaExample:CheckingIntroductiontoJavaObjective:CheckingwhetherastringisapalindromeignoringNon-alphanumericCharacters:astringthatreadsthesameforwardandbackward.Assumethelettersarenotcase-sensitiveP.255-256/**ReturntrueifastringisapalindromepublicstaticbooleanisPalindrome(String{//Createanewstringbyeliminatingnon-alphanumericcharsStrings1=//CreateanewstringthatisthereversalofStrings2=//Compareifthereversalisthesameastheoriginalreturns2.equals(s1);Example:CheckingPalindromesIgnoringNon-alphanumeric/**Createanewstringbyeliminatingnon-alphanumericchars*/publicstaticStringfilter(Strings)//CreateastringStringBufferstrBuf=new//Examineeachcharinthestringtoskipalphanumericcharfor(inti=0;i<s.length();i++)if{strBuf.append(s.charAt(i));}//ReturnanewfilteredreturnstrBuf.toString();CheckingPalindromesIgnoringNon-alphanumeric/**Createanewstringbyreversingaspecifiedstring*/publicstaticStringreverse(Strings){StringBufferstrBuf=newStringBuffer(s);//UsethereversemethodforStringBufferreturn}Command-LineInthemainmethod,gettheargumentsfromargs[0],args[1],...,args[n],whichcorrespondstoarg0,arg1,...,argninthecommandline.classTestMainpublicstaticvoidmain(String[]args) }javaTestMainarg0arg1arg2...Example:javaTestMain“firstnum”aiphaExample:UsingCommand-LineObjective:Writeaprogramthatwillperformbinaryoperationsonintegers.Theprogramreceivesthreeparameters:anoperatorandtwo ifif(args.length!=3)System.out.println("Usage:javaCalculatoroperand1operatoroperand2");javaCalculator2+javaCalculator2-javaCalculator2/javaCalculator2“*”RegularRegularexpressions(regex's)aresetsofsymbolsandsyntacticelementsusedtomatchpatternsoftextRegularexpressionsareanextremelyusefultoolformanipulatingtext,heavilyusedintheautomaticgenerationofWebinthespecificationofprogrammingintext Sincejdk1.4,Javahasaregularexpression Matchermbooleanb,IntroductiontoIntroductiontoJavastaticvoidPatternp=null;//正則表達式Matchermnull操作的字符串booleanb=false;p=Ppile("a*b");m=p.matcher("baaaaab");b=m.matches();p=Ppile("a*b");m=p.matcher("aaaaab");b=m.matches();publicstaticvoidmain(Stringargus[]){test();}

Basic.Matchesanysingle.at=cat,bat,rat,*Matcheszeroormoreoccurrencesofthesingleprecedingcharacter.*at=everythingthatendswithat0*123=123,0123,00123…MatchesanysinglecharacteroftheonescontainedMatchesanysinglecharacterexceptfortheonescontained[cbr]at=cat,bat,[^bc]at=rat,sat…,butnotbat,<[^>]*>=^Beginningof^a=linestartswith$Endof^$=blankline(startswiththeendofline)\Escapesfollowingspecial.\/&[]* \.\\\/\&\[\][cbr]at\.=matchescat.,bat.andrat.only…Charactera,b,orc(simpleAnycharacterexcepta,b,orcathroughz,orAthroughZ,inclusiveathroughd,ormthroughp:[a-dm-p]d,e,orfathroughz,exceptforbandc:[ad-z]athroughz,andnotmthroughp:[a-lq-z]PredefinedCharacter.Anycharacter(mayormaynotmatchlineAdigit:[0-Anon-digit:[^0-Awhitespace [Anon-whitespacecharacter:Awordcharacter:[a-zA-Z_0-Anon-wordcharacter:X,onceornotatX,zeroormoreX,oneormoreX,exactlynX,atleastnX,atleastnbutnotmorethanmtimespattern:xxx-xx-xxxx,xisadigitalregex:[\\d]{3}-[\\d]{2}-[\\d]{4}pattern:(xxx)xxx-xxxx,xisadigital,thefirstnumberisJavapattern:pattern:MonthJune26,RegularExpressionsin021-87888822 IntroductiontoJava IntroductiontoJavaRegularExpressionsinpublicbooleanmatches(StringStringregex="\\w{1,}@\\w{1,}\56\\w{1,}";Stringstr1="zhangsan@";Stringstr2=li@si@;RegularExpressionsinpublicStringreplaceAll(Stringregex,Stringreplacement)publicStringreplaceFirst(Stringregex,Stringreplacement)System.out.println(“JavaSystem.out.println(“JavaJavaJava”,replaceAll(“v\\w”,Output:JawijawiSystem.out.println(“JavaJavaJava”,replaceFirst(“v\\w”,Output:JawiJavaIntroductiontoJavaIntroductiontoJavapublicString[]split(StringpublicString[]split(Stringregex,intlimit)string"boo:and:foo” {"boo","and","foo" {"b","",":and:f"} {"boo","and:foo" {"boo","and","foo" {"boo","and","foo" {"b","",":and:f","","" - {"b","",":and:f","","" {"b","",":and:f"TheFileTheFileclassprovidesseveralcommonmanipulationsthatareusefulwithfilenames.Itprovidesmethodstoseparatepathnamesintosubcomponents,andforqueryingthefilesystemaboutthefileapathnamereferstopublicFile(Stringpath):CreatesaFileobjecttomanipulatethespecifiedpath.ThismethodthrowsaNullPointerExceptionifthepathparameterisnull publicFile(StringdirName,Stringname)File(dirName+File.separator+name) File(fileDir.getPath(),name) Filef1=newFile(“/”);Filef2=newFilef3=new

TheFileget:retrieveinformationaboutcomponentsofaFileobject?sexists:returnstrueifthefileexistsinthefilecanRead:returnstrueifthefileexistsandcanbecanWrite:returnstrueifthefileexistsandcanbeisFile:returnstrueifthefileisanormalisDirectory:returnstrueifthefileisaisAbsolute:returnstrueifthepathisanabsolutepubliclonglastModified():returnsthelastmodificationTheFilepubliclonglength():returnsthefilelengthinpublicbooleanmkdir():Createsadirectory,returningtrueonsuccesspublicbooleanmkdirs():Createsalldirectoriesinthispath,returningtrueifallwerecreatedpublicbooleanrenameTo(Filenew_name):Renamesafile,returningtrueiftherenamesucceededpublicbooleandelete():DeletesthefileordirectorynamedinthisFileobject,returningtrueifthedeletionpublicString[]list():Listsallfilesinadirectoryexcepttheequivalentof“.”and“..”TheFilepublicString[]list(FilenameFilterfilter):Usesthespecifiedfiltertolistfilesinadirectoryequals:trueiftwofileobjectshavethesamepath,notiftheyrefertothesameunderlyingfilesystemobjectFilesarecreatedusingPrintWriter、objectsorRandomAccessFileobjects,notusingFileThecharacterFile.pathSeparatorCharandthestringFile.pathSeparatorrepresentthecharacterthatseparatesfileordirectorynamesinasearchpathimport

IntroductiontoJavapublicIntroductiontoJavapublicstaticvoidmain(Stri

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論