Upload
doandan
View
218
Download
0
Embed Size (px)
Citation preview
DPCompSci.Java.1718.notebook
1
April29,2018
OptionDOOP
DPCompSci.Java.1718.notebook
2
April29,2018
Conditionals
intx=10if(x
DPCompSci.Java.1718.notebook
3
April29,2018
Loops
intx=10
while(x12)breakx++
}while(x
DPCompSci.Java.1718.notebook
4
April29,2018
KeyboardInput
importjava.util.Scannerimportjava.io.* //optionalifyouwanttodeclareSystem.in...
voidechoMe(){
Scannerkeyboard=newScanner(newInputStreamReader(System.in))
System.out.println("Entersometext:")
StringinStr=keyboard.nextLine()
System.out.println("Youanswered:"+inStr+":")
}
KeyboardInputusingScanner
TheScannerclasshandleskeyboardinput
Theclassisinjava.utilsoyouneedtoimportjava.util.Scannertouseit
StartbycreatinganinstanceofaScannerobject.
Scannerobjectshavelotsofmethodstoreadandinterpretinputfromthekeyboard.
YoucanconnecttheScannerclasstovariousinputsourcestheconsole,files,strings,etc.
variable keyboard points to an object of type Scanner
System.in identifies the "standard system input" as the source to be scanned. This is the console.
Scanner objects have a nextLine() method that waits for the user to type something then returns the line entered.
JavaTutorials
SomeofthemoreusefulmethodsoftheScannerclassare:
booleanhasNext(Stringpattern)
Thismethodreturnstrueifthenexttokenmatchesthepatternconstructedfromthespecifiedstring.
booleanhasNextInt()and booleanhasNext()
Thismethodreturnstrueifthenexttokeninthisscanner'sinputcanbeinterpretedasanintvalueinthedefaultradixusingthenextInt()method.
Stringnext(Stringpattern)
Thismethodreturnsthenexttokenifitmatchesthepatternconstructedfromthespecifiedstring.
intnextInt()and next()
Thismethodscansthenexttokenoftheinputasanint.
StringnextLine()
Thismethodadvancesthisscannerpastthecurrentlineandreturnstheinputthatwasskipped.
TheBufferedReaderclassisanotherwaytohandlekeyboardinput
Theclassinheritsfromjava.io.Readerandjava.io.InputStreamReadersoyouneedtoimportthemboth
Usethisclasswhenyoudonotneedtoparsetheinputbutwanttoreadcompletelines.
SeemoreatOracle'sBufferedReaderpage
KeyboardInputusingBufferedReader
https://www.tutorialspoint.com/java/util/java_util_scanner.htmhttps://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html
DPCompSci.Java.1718.notebook
5
April29,2018
FileInput
importjava.util.Scannerimportjava.io.* //optionalifyouwanttodeclareSystem.in...
voidReadFile(){
try{
System.out.print("Enterthefilenamewithextension:")
Scannerinput=newScanner(newInputStreamReader(System.in))
FileinFile=newFile(input.nextLine())
input=newScanner(inFile)
while(input.hasNextLine()){
Stringline=input.nextLine()
System.out.println(line)
}
input.close()
}catch(Exceptionex){
ex.printStackTrace()
}
}
FileInputusingScanner
TheScannerclassalsohandlesfileinput
ConnectyourScannerobjecttoafilewhenyouinstantiateit.
JavaTutorials
TheBufferedReaderclassisanotherwaytohandlekeyboardinput
Theclassinheritsfromjava.io.Readerandjava.io.InputStreamReadersoyouneedtoimportthemboth
Usethisclasswhenyoudonotneedtoparsetheinputbutwanttoreadcompletelines.
SeemoreatOracle'sBufferedReaderpage
KeyboardInputusingBufferedReader
https://www.tutorialspoint.com/java/util/java_util_scanner.htmhttps://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html
DPCompSci.Java.1718.notebook
6
April29,2018
3/26/18:Q4Start
OverviewofQ4
JavaDocumentationFileOperations
FileChooserGraphics
CreateaFrameGUIsinNetBeans
ArraysLinkedLists
ConceptsOOPideasAlgorithmsStartonIA
MainAssignmentsMiniProjectIAClient&SolutionIAConceptualPrototype
Someresources: Kjellonlinebook CodingBat ProgrammingbyDoing
http://chortle.ccsu.edu/Java5/index.html#24http://codingbat.com/javahttps://programmingbydoing.com/
DPCompSci.Java.1718.notebook
7
April29,2018
3/26FileIO
Wherearewe?YoushouldhaveaTestFileScannerclassinyourExercisesprojectsimilartotheonebelow.HowdidIgetthisdocumentation?Let'slook.
Today:StartanewBlueJprojectcalledGUITools.Init,createaclasscalledTestGUIFileIOOurfirstmethodwillbechooseFilewhichusesJava'sJFileChooserclass.
publicFilechooseFile(Stringtitle,StringdefName){JFileChooserfc=newJFileChooser()fc.setDialogTitle(title)fc.setCurrentDirectory(newFile(defName))fc.setSelectedFile(newFile(defName))intresult=fc.showOpenDialog(null)if(result==JFileChooser.APPROVE_OPTION){
System.out.println("Chose"+fc.getSelectedFile()) //debugreturnfc.getSelectedFile()
}System.out.println("Usercancelled") //debugreturnnull
}
JFileChooserisverypowerful.Lookatsomeofitsotherfeaturesto,forexample,showonlydirectories,managethelookandfeel,filtertoonlycertainfiletypes,etc.
Fromnowon,youwillbeexpectedtodocumentyourcode,withaminimumofaheaderforeachclassandmethod.Youmaydothisafterthecodeisdebuggedandworking,butanythingthatyouturninmustbedocumented.
HW:ReadKjell,Ch23Review&Exercise5or6
3/26/18
https://docs.oracle.com/javase/8/docs/api/index.htmlhttp://chortle.ccsu.edu/Java5/Notes/chap23/ch23_1.html
DPCompSci.Java.1718.notebook
8
April29,2018
3/28FileIOCont
publicFilechooseFile(Stringtitle,StringbuttonText,StringdefName){
JFileChooserfc=newJFileChooser()fc.setDialogTitle(title)fc.setCurrentDirectory(newFile(defName))fc.setSelectedFile(newFile(defName))intresult=fc.showDialog(null,buttonText) //notshowOpenDialogif(result==JFileChooser.APPROVE_OPTION){
System.out.println("Chose"+fc.getSelectedFile()) //debugreturnfc.getSelectedFile()
}System.out.println("Usercancelled") //debugreturnnull
}
JFileChooserisverypowerful.Lookatsomeofitsotherfeaturesto,forexample,showonlydirectories,managethelookandfeel,filtertoonlycertainfiletypes,etc.
echoFile():UsechooseFiletocreateamethodthatopensatextfileandechoesthecontentstotheconsole.CallitechoFile().Hint:SeeyourreadFileWErrormethod.
keyboardToFile():UsechooseFiletoopenanoutputfileandenterlinesfromthekeyboardthatgetappendedtothatfile.CallitkeyboardToFile().Becarefulnottooverwriteafilethatyouwant.Andbesuretoclosethefile!
appendToFile():UsechooseFiletoopenaninputfileandanoutputfile.Appendthelinesfromtheinputfiletotheendoftheoutputfile.CallitappendToFile().Becarefulnottooverwriteafilethatyouwant.Andbesuretoclosebothfiles!
loopThroughFile():UsechooseFiletoopenaninputfileandanoutputfile.Loopthroughthelinesfromtheinputfileandwritethemtotheoutputfile,overwritingitifitexists!CallitLoopThroughFile().Becarefulnottooverwriteafilethatyouwant.Andbesuretoclosebothfiles!
NoticethatloopThroughFile()thiscouldbedonedirectlywithJava'sFiles.copy()method.Whywriteourownloop?Wenowhaveatemplateforloopingthroughthelinesofafile,processingtheminsomeway,andthenwritingtheprocessedlinetotheoutputfile.Verypowerful!
HW:ReadKjell,Ch23Review&Exercise5or6
HW:ReadKjell,Ch24
Monday3/26
Wednesday3/28
3/26/18
Toavoidthisinconsistency,IfoundthatwecanuseshowDialoginstead.ItismorecustomizablethanshowOpenDialogandworksthesameonOSXorWindows.Whew!
publicFilechooseFile(Stringtitle,StringdefName){JFileChooserfc=newJFileChooser()fc.setDialogTitle(title)fc.setCurrentDirectory(newFile(defName))fc.setSelectedFile(newFile(defName))intresult=fc.showOpenDialog(null)if(result==JFileChooser.APPROVE_OPTION){
System.out.println("Chose"+fc.getSelectedFile()) //debugreturnfc.getSelectedFile()
}System.out.println("Usercancelled") //debugreturnnull
}
Here'sthecodeweusedonMondaytoselectafile:
Wesawthat,onaMac,theshowOpenDialogmethodwasnotallowingustotypeinafilename.
ThesamecodeworksdifferentlyinWindows!
Optiontotypeinfilename
3/28/18
https://docs.oracle.com/javase/8/docs/api/index.htmlhttp://chortle.ccsu.edu/Java5/Notes/chap23/ch23_1.htmlhttp://chortle.ccsu.edu/Java5/Notes/chap24/ch24_1.html
DPCompSci.Java.1718.notebook
9
April29,2018
4/2Questions
Classes a"SourceCode"file(text.java) a"Compiled"file(binary.class)
> Madeby"compiling"the"sourcecode"into"machinecode"(1's&0's)
a"ClassContext"file(text.ctxt)> A"Buildinstructionfile"
4/2/18
Aswegetintomorecomplicatedterritory,Let'stakeatimeouttogobackandreviewsomeofthebasicconstructsthatwe'veseen:
Projects
Packages
...inJava
...inBlueJ
...inNetBeans(later)
Methodsvs.Functions Basicallythesame Methodsareimplicitly
calledbyanobject,andso,haveaccesstoinformationabouttheparentobject(this).
Javadoesn'treallyhave"functions"sinceallprocessesaredefinedinaClassandhence,calledmethods.
...laterinthesamefile...
...later.stillinthesamefile...
Method(defining)
Methods(calling).
Method(defining)
"Calling"Parameters
ReturnValueNote:TypemustbeFile
ReturnsaValueoftype"File"
Fromanotherpointofview:Variables,runtime,&flowcontrol
...laterinthesamefile...
...later.stillinthesamefile...
At"Runtime" Eventsthatoccurduringthetimethattheprogramisrunning.
FileContentOrganizationimportsmain()(...later...)Classe(s) Classmethods localfunctions
ProgramOrganization Projects Packages Classes Objects Methods Functions Variables
> "primitive"types> Advanced?,Composite?,Civilized?types
Programcreation(building) SourceCode CompiledCode "Build"or"Make"instructionfiles. Run
Programflowcontrol(statements) Syntax Ifthen Ifthenelse whileloops dowhileloops forloops trycatch
Objects ...onlyexistatruntime. ...arespecific"instances"ofaClass ..."carrywiththem"thefieldsandmethodsoftheparentClass ...aregenerallycreatedwitha"constructor"methodoftheClassusingnew.
To"run"appendFile(),forexample CompileTestGUIFileIO(BlueJcreates.classfile)
> Compilers"import"supportingclasses InstantiateanewTestGUIFileIOobject
> Canbedoneinthecodewitha"constructor"method:new
ExecuteamethodfromtheObject> Ifneeded,BlueJwillpromptyouforparameters
VariablesoftypeFile
TryCatchconstruction while
loop
forloop
primitivetypeint
conditionalblockif
"Instantiate"anewobjectfromtheclassJFileChooserusingnew"fcisaJfileChooserobject"
Let'slookatyourKjellExercise23.5or23.6
Whichofthesedoyouhavefinished?
keyboardToFile():UsechooseFiletoopenanoutputfileandenterlinesfromthekeyboardthatgetappendedtothatfile.CallitkeyboardToFile().Becarefulnottooverwriteafilethatyouwant.Andbesuretoclosethefile!
echoFile():UsechooseFiletocreateamethodthatopensatextfileandechoesthecontentstotheconsole.CallitechoFile().Hint:SeeyourreadFileWErrormethod.
PseudocodeforkeyboardToFile
Chooseafile(theoutputfile)CreateaninputScannerobjectfromthekeyboardWritesomegeneralinstructionstotheuserontheconsoleTryto
CreateaPrintwriterconnectedtotheoutputfilePrintaprompt,suchas">",totheconsoleGetthenextlineofinputfromtheconsoleintoastringAslongasthestringisnotofzerolength
PrintthenextlinePrintanotherprompt(">")Getthenextlinefromtheconsole
ClosethePrintWriterwhenfinished(.close()method)CatchanyIOexceptionswithastacktraceClosetheconsole
PrintWriter
DPCompSci.Java.1718.notebook
10
April29,2018
4/4MoreFileIO
1. 2. 3. Inthecodeshown,
howdoestheuserentertheinputfilename?Inwhatline? [2]
4. Nameatleast2problemswiththistechnique. [2]
5. Nameabettertechnique. [1]
6. Whatline(s)ofcodecouldyouchangetomakeiteasierfortheusertoenteravalidfilename? [2]
7. Describehowyouwoulddothat.Beasspecificasyoucan. [4]
HWQuiz:
1. Generallyspeaking,whatdoesthecodeattherightdo?
2. Fillinthevaluesthatbelonginline:
18: 0 [1]24: sizeA [1]27: sumA=sumA+value
[1]28: count++ [1]32: sumA/sizeA [1]
4/4/18
HW:WriteyesNo()
appendToFile():UsechooseFiletoopenaninputfileandanoutputfile.Appendthelinesfromtheinputfiletotheendoftheoutputfile.CallitappendToFile().Becarefulnottooverwriteafilethatyouwant.Andbesuretoclosebothfiles!
loopThroughFile():UsechooseFiletoopenaninputfileandanoutputfile.Loopthroughthelinesfromtheinputfileandwritethemtotheoutputfile,overwritingitifitexists!CallitLoopThroughFile().Becarefulnottooverwriteafilethatyouwant.Andbesuretoclosebothfiles!
NoticethatloopThroughFile()thiscouldbedonedirectlywithJava'sFiles.copy()method.Whywriteourownloop?Wenowhaveatemplateforloopingthroughthelinesofafile,processingtheminsomeway,andthenwritingtheprocessedlinetotheoutputfile.Verypowerful!
DPCompSci.Java.1718.notebook
11
April29,2018
4/9Netbeans
Kjell:ReadCh46HW:PBD136:Alittlepuzzle
Hint:OnPBD136youneedtodoalittletricktouseScannertoreadonecharacteratatime.
4/9/18
Download,installNetBeans CreatingagraphicaluserinterfacewithNetBeans
PBD136:Openafilespecifiedbytheuser.Thisfilewillcontainabunchofcharacters.Youshouldreadineachcharacterfromthefile,onecharacteratatime.Displayeverythirdcharacteronthescreen.Throwtheothercharactersaway.Thereisasampleinputfilecalledpuzzle.txt,containingalittlemessageyoucanusetotestyourprogram.Forfun,the"thrownaway"charactersmightsaysomething,too,incaseyoucaretotrytoviewthemsomehow.
CreateaNetBeansProjectsfoldersomewhereonyourcomputerwhereyoucanfindit(likein..\Desert\1718\IBCompSci\NetBeansProjects)StartanewprojectcalledNBExercisesinyourNetBeansProjectsfolder.IdentifytheMainclassasnbexercises.NBExercises.Createamainmethod
Themain()method Alljavaprogramsthatruninastandaloneenvironmentneedamainmethod. Themainmethodcanbeinanyclassthatispartoftheprogram. TheJavavirtualmachinelooksforthemainmethodwhenaprogramisfirstrunto"get
started". Themainmethodcanbeinanyclassthatispartoftheprogram. Atypicalmainmethodmightlooklike:publicstaticvoidmain(String[]args){try{//SetSystemL&FUIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())program=new
//thecodetorun(test?)goesbelowprogram.method1ToTest()//program.method2ToTest()}catch(Exceptione){e.printStackTrace()}System.exit(0)//necessary
}
This instantiates the class
Task:GetyourloopThroughFilemethodrunninginNetBeans IncludechooseFile(with3parametersandusingaparentdialog) IncludeyourworkingyesNo()method HowdidIgetthedefaultnameofthefiletocopyto?
Next,workonPBD136andfinishitforWed.
PseudocodeforPBD136Choosetheinputfile(puzzle.txtorpuzzle2.txt)Tryto
ConnecttheinputfiletoaScannerobject(sowecanreadit)Aslongasthereisanotherlineintheinputfile
GetthenextlineConnectthelinetoaScannersowecanloopthroughcharactersSetthedelimiterto""sowecangetonecharacteratatimeAslongasthelinehasanothercharacter
ifthepositionisamultipleof3printthecharactertotheconsole
Closetheinputfilewhenfinished(.close()method)CatchanyIOexceptionswithastacktrace
Kjell:ReadCh46HW:PBD136:Alittlepuzzle
All further programming work should be done in NetBeans
https://programmingbydoing.com/a/a-little-puzzle.htmlhttps://stackoverflow.com/questions/2597841/scanner-method-to-get-a-charhttps://www.youtube.com/watch?v=JZTIIchUa6Ehttps://programmingbydoing.com/a/a-little-puzzle.html
DPCompSci.Java.1718.notebook
12
April29,2018
4/11Arrays
int[]myIntArray //declareanarrayofintegersmyIntArray=newint[10] //createitwith10elements
char[]myCharArray=newchar[10] //a10elementarrayofchars
//youcaninitializetovaluesString[]myStringArray={"Pine","Fred","Avacado","granite"}
for(ints:){System.out.println("valueofx:"+x)
}
Arrays
Anorderedgroupofelements
ArraysareobjectsfromanArraysclass,withassociatedmethods
Elementscanbeprimitivetypesorobjects
Needtobedeclaredandcreated(canbedoneinonestatement)
Needtoknowthesizewhenit'screated
JavaTutorials
DotheseriesofexercisesPBD138141,BasicArrays.Pleasefollowtheinstructionsexactly.Emailmethe.javafilethatcontainsyourcode.ThemethodnamesshouldbePBD138,PBD139,PBD140,andPBD141
4/11/18
PBD138:Createanarraythatcanholdtenintegers.Fillupeachslotofthearraywiththenumber113.Thendisplaythecontentsofthearrayonthescreen,eachvalueonaseparaterow. Donotusealoop.Also,donotuseanyvariablefortheindexyoumustuseliteral
numberstorefertoeachslot.
PBD139:Createanarraythatcanholdtenintegers.Fillupeachslotofthearraywiththenumber113.Thendisplaythecontentsofthearrayonthescreen,eachvalueonaseparaterow. Thistime,youmustusealoop,toputthevaluesinthearrayandalsotodisplaythem.
Also,intheconditionofyourloop,youshouldnotcountuptoaliteralnumber.Insteadyoushouldusethelengthfieldofyourarray.
PBD140:Createanarraythatcanholdtenintegers.Fillupeachslotofthearraywitharandomnumberfrom1to100.Thendisplaythecontentsofthearrayonthescreen. Youmustusealooptofillthearray. And,likelasttime,youmustusethelengthfieldofyourarrayandnotaliteral
number(like10)intheconditionoftheloop.
PBD141:Createanarraythatcanhold1000integers.Fillthearraywithrandomnumbersintherange1099.Thendisplaythecontentsofthearrayonthescreeninrowsof20. Youmustusealooptofillthearray. Ifyou'recarefultoonlypickrandomnumbersfrom10to99andyouputtwospaces
aftereachnumber,thenyouroutputwilllineupasbelow. Andifyoudon'tknowhowtopickrandomnumbersinacertainrange,seethe
HW:PBD138141BasicArrays
HW:PBD138141BasicArrays
nextInt()methodoftheRandomclassinJavadocs.
https://www.tutorialspoint.com/java/java_arrays.htmhttps://programmingbydoing.com/a/basic-arrays-0.htmlhttps://programmingbydoing.com/a/basic-arrays-1.htmlhttps://programmingbydoing.com/a/basic-arrays-2.htmlhttps://programmingbydoing.com/a/basic-arrays-3.htmlhttps://programmingbydoing.com/a/basic-arrays-0.htmlhttps://programmingbydoing.com/a/basic-arrays-0.htmlhttps://docs.oracle.com/javase/8/docs/api/java/util/Random.html#nextInt-int-
DPCompSci.Java.1718.notebook
13
April29,2018
4/13Arrayalgorithms
JavaTutorials
4/13/18
Inclasstoday,youwillworkonKjell:Ch47
HW:KjellCh47Ex46Onceyouhavereadit,workonExercises46FinishforMonday
JavaTutorials
4/16/184/20/18
Inclasstoday,andWedwewillworkonKjell:Ch49C(2DArrays)
HW:KjellCh49CExercises1,2,4,5,6&7(optional)
Onceyouhavereadit,workonExercises1,2,4,5,6&7(optional)FinishforMonday4/23
4/23/184/27/18 Morewitharraysandsorting
https://www.tutorialspoint.com/java/java_arrays.htmhttp://chortle.ccsu.edu/Java5/Notes/chap47/ch47_1.htmlhttp://chortle.ccsu.edu/Java5/Notes/chap47/progExercises47.htmlhttps://www.tutorialspoint.com/java/java_arrays.htmhttp://chortle.ccsu.edu/Java5/Notes/chap47/ch47_1.htmlhttp://chortle.ccsu.edu/Java5/Notes/chap49C/progExercises49C.html
DPCompSci.Java.1718.notebook
14
April29,2018
4/27Arrayalgorithms
4/27/18
37 12 20 16 8 44 19
SortingAlgorithms
ExchangesortForeachelementinthearray,startingwiththefirstone:
CompareeachoftheremainingelementstothefirstoneIfanyelementislargerthanthefirstone,swapthetwo.
i3
DPCompSci.Java.1718.notebook
15
April29,2018
5/2GraphicsIntro
4/30/18
PBD160:Bubblesort PBD161:Selectionsort
5/2/18
KjellCh36:GraphicsHW:KjellCh36Exercises16
5/4/18
KjellCh37:MoregraphicsideasHW:KjellCh37MiniProject(DueWed,5/9)
http://www.algolist.net/Algorithms/Sorting/Bubble_sorthttp://www.algolist.net/Algorithms/Sorting/Selection_sorthttp://chortle.ccsu.edu/Java5/Notes/chap36new/ch36_1.htmlhttp://chortle.ccsu.edu/Java5/Notes/chap36new/progExercises36.htmlhttp://chortle.ccsu.edu/Java5/Notes/chap36new/ch36_1.html
Attachments
JavaCheatSheet.pdf
DPCS.MiniProject.pdf
THE JAVA LANGUAGE CHEAT SHEET
Primitive Types: INTEGER: byte(8bit),short(16bit),int(32bit),
long(64bit),DECIM:float(32bit),double(64bit)
,OTHER: boolean(1bit), char (Unicode)
HEX:0x1AF,BINARY:0b00101,LONG:8888888888888L
CHAR EXAMPLES: a,\n,\t,\,\\,\
Primitive Operators Assignment Operator: = (ex: int a=5,b=3; )
Binary Operators (two arguments): + - * / %
Unary Operators: + - ++ --
Boolean Not Operator (Unary): !
Boolean Binary: == != > >= < >>>
Ternary Operator: bool?valtrue:valfalse;
Casting, Conversion int x = (int)5.5; //works for numeric types
int x = Integer.parseInt(123);
float y = Float.parseFloat(1.5);
int x = Integer.parseInt(7A,16); //fromHex
String hex = Integer.toString(99,16);//toHex
//Previous lines work w/ binary, other bases
java.util.Scanner, input, output Scanner sc = new Scanner(System.in);
int i = sc.nextInt(); //stops at whitespace
String line = sc.nextLine(); //whole line
System.out.println(bla); //stdout
System.err.print(bla); //stderr,no newline
java.lang.Number types Integer x = 5; double y = x.doubleValue();
double y = (double)x.intValue();
//Many other methods for Long, Double, etc
java.lang.String Methods //Operator +, e.g. fat+cat -> fatcat
boolean equals(String other);
int length();
char charAt(int i);
String substring(int i, int j); //j not incl
boolean contains(String sub);
boolean startsWith(String pre);
boolean endsWith(String post);
int indexOf(String p); //-1 if not found
int indexOf(String p, int i); //start at i
int compareTo(String t);
//a.compareTo(b) -> -1
String replaceAll(String str, String find);
String[] split(String delim);
StringBuffer, StringBuilder StringBuffer is synchronized StringBuilder
(Use StringBuilder unless multithreaded)
Use the .apend( xyz ) methods to concat
toString() converts back to String
java.lang.Math Math.abs(NUM),Math.ceil(NUM),Math.floor(NUM)
,Math.log(NUM),Math.max(A,B),Math.min(C,D),
Math.pow(A,B),Math.round(A),Math.random()
IF STATEMENTS: if( boolean_value ) { STATEMENTS }
else if( bool ) { STATEMENTS }
else if( ..etc ) { STATEMENTS }
else { STATEMENTS }
//curly brackets optional if one line
LOOPS: while( bool ) { STATEMENTS }
for(INIT;BOOL;UPDATE) { STATEMENTS }
//1INIT 2BOOL 3STATEMENTS 4UPDATE 5->Step2
do{ STATEMENTS }while( bool );
//do loops run at least once before checking
break; //ends enclosing loop (exit loop)
continue; //jumps to bottom of loop
ARRAYS: int[] x = new int[10]; //ten zeros
int[][] x = new int[5][5]; //5 by 5 matrix
int[] x = {1,2,3,4};
x.length; //int expression length of array
int[][] x = {{1,2},{3,4,5}}; //ragged array
String[] y = new String[10]; //10 nulls
//Note that object types are null by default
//loop through array:
for(int i=0;i
POLYMORPHISM: Single Inheritance with extends
class A{ }
class B extends A{ }
abstract class C { }
class D extends C { }
class E extends D
Abstract methods
abstract class F {
abstract int bla();
}
class G extends F {
int bla() { //required method
return 5;
}
}
Multiple Inheritance of interfaces with
implements (fields not inherited)
interface H {
void methodA();
boolean methodB(int arg);
}
interface I extends H{
void methodC();
}
interface K {}
class J extends F implements I, K {
int bla() { return 5; } //required from F
void methodA(){} //required from H
boolean methodB(int a) { //req from A
return 1;
}
void methodC(){} //required from I
}
Type inference:
A x = new B(); //OK
B y = new A(); //Not OK
C z = new C(); //Cannot instantiate abstract
//Method calls care about right hand type
(the instantiated object)
//Compiler checks depend on left hand type
GENERICS: class MyClass {
T value;
T getValue() { return value; }
}
class ExampleTwo {
A x;
B y;
}
class ExampleThree {
A list;
B head;
}
//Note the extends keyword here applies as
well to interfaces, so A can be an interface
that extends List
JAVA COLLECTIONS: List: Similar to arrays
ArrayList: Slow insert into middle
//ArrayList has fast random access
LinkedList: slow random access
//LinkedList fast as queue/stack
Stack: Removes and adds from end
List Usage:
boolean add(T e);
void clear(); //empties
boolean contains(Object o);
T get(int index);
T remove(int index);
boolean remove(Object o);
//remove uses comparator
T set(int index, E val);
Int size();
List Traversal:
for(int i=0i
DP Computer Science: Mini-Project Alei 2017-18
C:\Users\Bob\Documents\Dropbox\Desert\DP CompSci\DPCompSciNotes.docx on 4/28/18 at 9:11 PM Page 1 of 1
Create your own picture Description: Create a program that draws a picture illustrating some of what we have recently learned about arrays and graphics. This is an individual project. You may not work together. If you have questions or need help debugging, you may ask me or anyone else who is not in the course. Requirements: Your program should create a JPanel within a JFrame window that:
Includes at least one each of line, oval (or circle), rectangle, and polygon
Uses a background color other than the default
Uses at least three different colors of fill
Uses at least one custom color that is not a predefined Java constant
Has some elements other than lines that scale with the size of the window
Contains at least one repeated element with properties controlled by one or more arrays
Exits when the red x box is pressed. Deliverables:
The .java file containing your main class and any other classes that you create.
A screen shot of the picture(s) that your code produces
A hand drawn, scale diagram on a grid indicating the shapes that make up your drawing along with their initial sizes and positions.
Assessment Rubric:
A. Creativity
0-1 Shows little or no creativity
2-3 Shows some creativity
4-5 Shows a lot of creativity
B. Complexity
0-1 Does not meet the minimum requirements
2-3 Meets the minimum requirements
4-5 Above and beyond the minimum requirements
C. Coding Style
0-1 Poor formatting Minimal or no documentation Inefficient or incorrect use of code repetition, hard coded values, etc. Poor choice of variable names
2-3 Some incorrect formatting Missing documentation Reasonably efficient and mostly correct use of code Mostly appropriate choices for variable names
4-5 Good use of formatting to make the code readable Complete but concise documentation, including inline comments as appropriate Very efficient and correct use of code minimal repetition, creative use of methods Thoughtful choices for all variable names
Hint: Start with a simple design that meets the requirements. Write clean code. Then add creativity and complexity.
SMART Notebook
Page 1Page 2Page 3Page 4Page 5Page 6Page 7Page 8Page 9Page 10Page 11Page 12Page 13Page 14Page 15Attachments Page 1