计算机编程JAVA课堂笔记美国威斯康辛大学麦迪逊分校Word文档下载推荐.docx
《计算机编程JAVA课堂笔记美国威斯康辛大学麦迪逊分校Word文档下载推荐.docx》由会员分享,可在线阅读,更多相关《计算机编程JAVA课堂笔记美国威斯康辛大学麦迪逊分校Word文档下载推荐.docx(31页珍藏版)》请在冰豆网上搜索。
languageshumansusetocommunicate,whicharefullofambiguity
∙Formallanguages:
preciseandunambiguouslanguagesusedtocommunicatespecificideas
∙Algorithms–basics
∙Howdowedetermineifanalgorithmworksasdesired?
oWecarefullyperformthealgorithmtoseewhatresults.Itworksifwegetthedesiredoutcome
oWecallthistracing
∙Algorithms–execution
∙Weassume:
otheywillstartatthebeginning/top
otheywilldoinstructionsinorder,oneafteranother,formthetoptothebottom(sequencing)
otheywillstopattheend/bottom
∙Algorithms–Criteria
∙Whatmakesitgood:
oItworksasdesired
oItisefficient(takefewersteps)
oItisrobust(handleerrorswell)
oItisuserfriendly
oItisclear(well-structured,well-documented)
oItisgeneral
∙1stJavaProgram:
Class
∙What’saclass?
oItisacontainerforaprogram’scode
oStartclassnameswithanUppercaseletter
File
∙What’safile?
oItisacontainerofrelatedinfothat’skeptinsecondarystorage
main
∙What’samethod?
oItisacontainerforinstructionsthatdoaparticulartaskorsolveaparticularpartofaproblem
oJavaprogramsbeginexecutingatthefirstinstructioninthemainmethodandstopafterexecutingthelastinstructioninmain
Statement
∙What’sastatement?
oIt’sainstruction!
Therearemanydifferentkindsofstatementsandtheyendwithasemicolon;
oItdisplayswhat’sbetweentheparentheses
oprintlnfollowstheoutputwithanewline,whereasprintdoesnot
Developing
∙Eclipse:
oEditing:
enteringtextintoasourcefile(.java)
oCompiling:
translatingthesourcefiletoaclassfile(.class)
oRunning:
usingtheJVMtoexecutetheclassfile
publicclassIRemember{
publicstaticvoidmain(String[]args)
{
System.out.println("
IRemember!
"
);
}
}
2ndJavaProgram:
Commenting
∙/*multiline
comment*/
∙//singlelinecomment
∙commentsmakeprogramsmoreunderstandable,butareignoredbythecompiler
∙CS302hasspecificcommentingstandards(seeonlineCS302commentingguide)’
Braces
∙{}:
recallthataclassandamethodarecontainers,Bracesmarkthebeginningandendingofthosecontainers
obody:
what’sbetween{}
oheadings:
whatcomesbefore{
∙makesureeveryopeningbrace{
hasamatchingclosingbrace}
ReservedWords
∙what’sareservedword?
oIt’saworddefinedbythePLtohaveaspecificpurpose
∙Listallofthereservedwordsintheprogramabove:
oPublic,class,static,void
∙Reservedwordscannotbeusedfornamingthings.
identifiers
∙what’sanidentifier?
oIt’sanamewegivetoaclass,amethod,avariable,etc.
∙Listalloftheidentifiersintheprogramabove:
oClasses:
IRemember,String,System
oMethods:
main,println
oVariables:
args,out
∙Whenchoosingidentifiersnamingrulesmustbefollowed(seeonlineCS302styleguide)
Volumes
∙What’savariable?
oIt’sacontainerforasinglevaluethatcanchange
oItcanstoreonlyoneparticulartypeofdata
∙Howdoesthecomputerknowthevariable’stype?
oBeforeavariablecanbeused,itstypeisspecifiedinadeclarationstatement.Theformis:
<
type>
<
listofvariablesseparatedbycommas>
;
∙Byconvention,weputvariabledeclarationstatementsatthebeginningofamethod
NumericDataTypes
∙Ifavariableholdsawholenumber,whattypeshouldbeused?
ointiftherangeofvariableis-2to+2billion
owecalltheseintegers
∙ifavariableholdsarealnumber
odoubleiftherangeofvalueis–3.4*10308to+3.4*10308
owecallthesefloating-pointvariables
3rdJavaProgram:
Variables
∙Howisavariablegivenavalue?
oEitherbyinitializingitinthedeclarationstatementorbyusinganassignmentstatement
∙Whenreadinganassignmentstatementreplacethe=withtheword“gets”.Forexample:
omonth=12;
“monthGETS12”
AssignmentStatements
∙FormoftheAssignmentStatement:
variable>
=<
value,variable,orexpression>
oLHSof=isavariable
oRHSof=canbe:
▪Aliteralvalue:
count=112233;
▪Avariable:
count=numberOfStudents;
▪Anexpression:
count=count+1;
∙CommasareNOTallowedinnumbers!
112,233resultsinacompile-timeerror.
∙Tracingassignmentstatements:
o1.Firstfigureoutthevalueoftheresultontheright
o2.Thenassignthatvaluetothevariableontheleft
MixingNumericTypes
∙Assigninganintegervalueintoafloating-pointvariableworksjustfine:
doubleaccountBalance=1000;
∙Assigningafloating-pointvalueintoanintegervariabledoesNOTwork!
intnumberOfStudents=22.11;
oWhy?
It’sliketryingtocramalargeobjectintoasmallbox.Itdoesn’tfitandthat’sillegal.
oTodothisyoumustuseatypecast:
intnumberOfStudents=(int)22.11;
oDoesthiswork?
intcount=0.0;
No!
Constants
∙What’saconstant?
oIt’sasinglevaluethatCANNOTchange(duringexecution)
oItcaneitherbeanexplicitvalue(calledaliteralorhard-codedconstant),oritcanbeanamedconstant(justcallaconstant).
∙Usenamedconstantstomakeyourprogrammoreunderstandableandeasiertoupdate/correct!
∙Examplesofliteralconstants:
11,1234567,-2integerconstants
.009,8.,3.77floating-pointconstants
“string”,“howdy”stringconstants
∙Writenamedconstantfor3.2%interestrate:
finaldoubleINTEREST_RATE=.032;
Form:
final<
CONSTANT_NAME>
value>
∙Allnamedconstantsusethefinalmodifier
whichtellsthecompilerthisisthefinalvalueitgets.
Expressions
∙Expression:
it’sacombinationofoperatorsandoperandsthatisevaluatedtoobtainaresultvalue.
∙Operator:
it’sasymbolthatinstructsthecomputertoperformabasicactionononeormoreoperands.
∙Operand:
it’saliteral,constant,variable,resultfromanotherexpression,avaluereturnedbyamethod,orothersourceofinformation
BasicArithmeticOperators
∙Basicmathematicaloperationsaredefinedforintegerandfloating-pointtypesincluding:
oBinaryoperations:
+,-,*,/,%
oUnaryoperations:
+plussign;
-minussign
∙Divisiondependsonthetypeofoperands!
∙Integersalsohaveremainderdivision(%modulus)
IncrementandDecrementOperators
∙Addingorsubtractingby1arecommonoperations:
ocount=count+1;
//increment
ocount=count–1;
//decrement
∙Instead,usethese(unary)operators:
ocount++;
ocount––;
∙Use++and–instatementsbythemselves(asshown)toavoidconfusingresults
∙Updatingavariablebasedonitsoriginalvalueisanothercommonoperation
Writingprogramsuserfriendly!
∙UserinputmakesourprogramsmoreGENERAL!
∙Algorithmforcalculatingprograms(rectanglearea):
o1.Getinput(readlengthandwidth)
o2.Calculatetheresult(areaislength*width)
o3.Outputtheresult(displayarea)
∙Thesestatementsconnecttheprogramtothekeyboard:
oimportjava.util.Scanner;
ScannerstdIn=newScanner(System.in);
∙
owidth=stdIn.nextDouble();
olength=stdIn.nextDouble();
Input–TheScannerClass
∙Javaprovidesapre-writtenclassnamedScanner,whichallowyoutogetinputfromauser.
∙Threethingsneededtousepre-writtenclasses:
o1.Tellthecompilerwheretogetthecodebyusinganimportstatement:
importjava.util.Scanner;
o2.Makeasoftwareobjectbydeclaringandinitializingit:
o3.Usethesoftwareobjectbycallinmethodslikethese:
=stdIn.nextInt();
=stdIn.nextLine();
CharacterType–char
∙Acharvariableholdsasinglecharacter(storedasanintegervalue)
∙Acharliteralissurroundedbysinglequotes,like‘B’,1,:
∙Whatisoutputbythiscode:
oCharfirst,middle,last;
oFirst=‘J’;
oMiddle=‘D’;
oLast=‘S’;
oSystem.out.println(“Hello”,+first+middle+last+”!
”);
StringClass
∙Stringisanotherpre-writtenclassfromwhichwecanmakesoftwareobjects(simplycalledobjects).Itdoestheworkofstoringanddoingtasksonsequencesofcharacterssuchaswords,phrases,etc.
∙Softwareobjectsmakeprogrammersmoreefficient!
∙TouseStrings:
o1.Wedon’tneedanimportstatement(butcouldhave):
importjava.lang.String;
//automaticallyimported
o2.WedoneedtomakeaStringobject:
Stringname1=“Deb”;
Stringname2=newString(“Jim”);
o3.wecanthenaskthestringobjecttodothetask:
∙Stringoperations
oAssignmentandinitializationusing=
oConcatenationusing+
∙StringMethods:
bycallingmethodswecandomanyusefulthingswithstrings
oLength:
returnsthenumberofcharactersinstringobject
Stringname=“EnterFudd”;
System.out.print(name.length()+“letters”);
Output?
10letters
och