2. java language basics - ics.uci.eduminhaenl/class/java_class/v1/3. java basic_2.pdf · 2. java...
TRANSCRIPT
2.Javalanguagebasics:Condi&on,1Darray,andloop
MinhaengLee
Contents
• Cas7ngandconversion
• Condi7onalStatement(if)• Loop• Switch• Prac7ce(Mul7plica7onTable!)• Homework
Cas7ng
• Datatransferbetweentwodifferenttypes– E.g.fromintegertofloat/double– Use“(<type>)”beforesourcevariable
• E.g.doubletarget=(double)iAmInteger;
– Becarefulwhenbiggeronetosmallerone• Datalossexpected
– Float(3.4)toInteger(3)• E.g.cas7ngfromdoubletoshort
– 3.141592(double)à3(int)
Cas7ng(prac7ce)
• inta;floatb;doublec;booleand;
• inttodouble:(double)a• doubletofloat:(float)c• floattoint:(int)b• inttoboolean:(boolean)a(notpossible)
UsefulClassTypes
• String– Usedoublequota7on“”– Canstoresequenceofcharacters– Concatena7onusing+
• LONG=“small”+“small”;(LONG=“smallsmall”)
• FromothertypestoString– UsetoString– Everyclasshave– EveryclasscanbeprintedasStringtype
Conversion• InbuiltexplicitmethodinJava– IntegertoString– String“1000”toInteger1000
• FromStringtonumber– <Integer/Float/Double>.parse<Int/Float/Double>();– e.g.doubled=Double.parseDouble(stringValue);
• FromnumbertoString– UsetoString()thateveryclasshave
Conversion(prac7ce)• inttoString Integer.toString(value)• floattoString Float.toString(value)• doubletoString Double.toString(value)• Stringtoint Integer.parseInt(stringValue)• Stringtofloat Float.parseInt(floatValue)• Stringtodouble Double.parseInt(doubleValue)
• Integertoint (int)IntegerValue• Floattofloat (float)FloatValue• Doubletodouble (double)DoubleValue
MathNota7on• Operator
– +:plus– -:minus– *:mul7plica7on– /:division– %:remainingvalues(4%3:1,10%2:0)
• Mathfunc7ons– Math.<something>();– Math.sqrt(var);– Math.round(var);– Math.ceil(var);– Math.floor(var);– Math.pow(var,var);– Etc.
Shortnota7on
• UsedinC,C++,Java• ++,--– a++:a=a+1– a--:a=a-1
• +=,*=,/=,-=– a+=1:a=a+1– A*=10:A=A*10– …
Quickprac7ce
Booleantype
• Shouldbetrueorfalse• 0=false,otherwise=truebutspecificbooleanresultissuggested
• Cancompareonlytwocompa7blevariables
BooleanOperators
hjp://faculty.uoit.ca/sar7pi/courses/OO/f12/2.slides/ch05-decisions/ch05-HTML/ch05/images/boolean_operators.png
If,Ifelse,andelse• If(<condi*on>)<statement>;
– Ifgiven<condi7on>istrue,thenexecuteonlyone<statement>
• if(<condi*on>){<statements>}– Ifgiven<condi7on>istrue,thenexecute<statements>
• if(<condi*on>){<statement1>}else{<statements2>}– Ifgiven<condi7on1>istrue,thenexecute<statements1>,otherwise
executeonly<statements2>
• if(<condi*on1>){<statements1>}elseif(<condi*ons2>){<statements2>}else{<statements3>}– Ifgiven<condi7on1>istrue,thenexecute<statements1>,otherwise
execute<statements2>if<condi7on2>istrue,otherwiseexecute<statements3>
If,Ifelse,andelse
If,ifelse,andelse(prac7ce!)
• Peoplecandrinkbeerwhentheyareover20• Peoplecandrivewhentheyareover14• Writeacodethatprintwhatpeoplecando.• E.g.15->“candrivebutcannotdrinking”,21->”candriveand
drinking”,10->“cannotneitherdrivenordrinking”• Usenestedif
• Printgradefrom“A”…to“F”• Fromonesingleintegervalue(0–100)• Useif,ifelse,andelse.• 90–100:A• 80–90:B• 70–80:C• 60–70:D• 0–60:F
Prac7ce1
Prac7ce2
14
20
0
100age
Array• Storemul7pledatainasinglevariable• []indicates1D-array• <Type>[]<variablename>=new<Type>[<size>];• Needini7aliza7on– Usenewkeywordtoindicatememoryalloca7on– c.f.singlevariabledoesn’tneedtodoit
• Example:– Singleint:inta;– Mul7pleints:int[]a=newint[10];
Array-access• intarray:int[]a=newint[10];• Stringarray:String[]strArray=newString[10];
• Accessthefirstelement– Indexbeginswith0– Examples
• Store10tothefirstone:a[0]=10;• Getsecondnumberandstore:b=a[1];• Printthefirstone:System.out.println(a[0]);
• Usefulproperty:length– Returnsthelengthofarray– Example:a.length
Loop• While
– While(<condi7on>){<statement>}– Execute<statement>while<condi7on>istrue– Sequence:<condi7on>-<statement>-<condi7on>-<statement>…
• Do-While– Do{<statement>}While(<condi7on>)– SimilartoWhilebutexecute<statement>atleastone7me.– Sequence:<statement>-<condi7on-<statement>-<condi7on>…
• For– For([init];<condi7on>;[incremental]){<statement>}– Sequence:[init]-<condi7on>-<statement>-[incremental]-
<condi7on>-<statement>-[incremental]-….
• Breakneeded
Loop:while
12
3
1 2 3 2 3
Loop:Do-while
12
3
1 2 3 2 3
Loop:for
1 2 4 3 2
12
3
4
4 3
Let’sprac7ce:Timestable• Timestableforonenumber(ex.2)• Usingoneloop• Expectedoutput:
– 2x1=2– 2x2=4– 2x3=6– …
• Timestableformul7plenumber(ex2–5)• Usingnestedloop• Expectedoutput:
– 2x1=2,3x1=3,4x1=4,5x1=5– 2x2=4,3x2=6,4x2=8,5x2=10– ….
breakandcon7nue
• Break– Usedinloop– Stopcurrentloop
• ConJnue– Usedinloop– Skiprestofstatementandgonextitera7on
Example
Switch• Similartomul7pleifelsestatement• Onlypossiblewhenweuseintvariableandcondi7onalvaluecheck
whetheritisequal• Executefromcertaincasetotheend
• Switch<variable>{– Case<case1>:
• <statement1>;• break;
– Case<case2>:• <statement2>;• …• break;
– Default:• <defaultstatement>;
• }
If<variable>isequalto<case1>thenexecute<statement1>ElseIf<variable>isequalto<case2>thenexecute<statement2>…ElseExecute<defaultstatement>
Switch
ExactlySame?
Homework1.
• Mul7-line7mestable(2–9)• Usingtriplenestedloops– 2to5fortoprow– 6to9forlowerrow
• Omitsimilarnumbermul7plica7on• Using“if”and“else”ontopofpreviousone– E.g.1x1,2x2,3x3…soon.