week09

week09 - Week 9: Methods CS 177 1 main() method We It have...

Info iconThis preview shows pages 1–7. Sign up to view the full content.

View Full Document Right Arrow Icon
CS 177 Week 9: Methods 1
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
main() method We have written lots of code so far It has all been inside of the main() method What about a big program? The main() method is going to get really long and hard to read Sometimes you need to do similar things several times: 2
Background image of page 2
Idea of a method Methods allow you to package some code to run over and over again Methods usually take some input (like numbers or Strings ) so that they can be parameterized Methods often give back an answer (like the square root of a number) Methods are called functions in some other languages 3
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Advantages of methods More modular programming Break a program into separate tasks Each task could be assigned to a different programmer Code reusability Use code over and over Could be in a code library (like Math.sqrt() ) Less code duplication 4
Background image of page 4
Anatomy of a method public static type name(type arg1,…,type argn) { statement1; statement2; statementm; } Required syntax Type of answer Name of last argument Name of 1st argument Name of method Type of 1st argument Type of last argument Code done by method 5
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Simple method example Given two integers, find the smaller: public static int min( int a, int b) { if ( a < b ) return a; else return b; } 6
Background image of page 6
Image of page 7
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 21

week09 - Week 9: Methods CS 177 1 main() method We It have...

This preview shows document pages 1 - 7. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online