Working with functions
Function definition of println
:
public void println(String x) {
if(x == null) {
x = "null";
}
try {
ensureOpen();
textOut.write(x);
} catch (IOException e) {
trouble = true;
}
newLine();
}
Function call:
System.out.println();
public
- access modifier
void
- return type
function()
- how we call our function
inside the function - block of code
Parameters and Arguments:
public void greeting(String location) {
System.out.println("Hello, " + location);
}
greeting("New York");
Randomly rolled dice:
/**
* This dice function simulates a 6 sided dice roll
*
* @return random value from 1 to 6
*/
public int rollDice() {
double randomNumber = Math.random(); // 0 to 0.999...
// A dice have 1 to 6
// i.e, so max value 6.9999 and min value of 1.00
randomNumber = randomNumber * 6
// shift range up one
randomNumber = randomNumber + 1;
int randomInt = (int) randomNumber; // casting
return randomInt;
}
int roll1 = rollDice(); //example, 2
int roll2 = rollDice(); //example, 4
Points on functions:
- Easy to reuse code
- Organize and group code
- More maintainable code
- Function definition is like a dictionary detail for a word in a sentence
- Argument order is important in a function call
-
Math.Random()
gives a random number between 0 and 1
Objects
Points on objects:
- Objects combine variables together to make your code meaningful
- Organized and maintainable code
--
https://docs.oracle.com/javase/8/docs/api/java/lang/package-summary.html
Top comments (0)