Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is an example of a method giving you a random dice roll:</p> <pre><code>public static int rollDice() { Random rand = new Random(); int roll = rand.nextInt(6) + 1; return roll; } </code></pre> <p>You would call the function like this:</p> <pre><code>int roll = rollDice(); </code></pre> <p>So it could be integrated in your program like this for example:</p> <pre><code>public static void main(String[] args) { //Display welcome message System.out.println("Welcome to the Math Functions event!"); Scanner keyIn = new Scanner(System.in); Scanner userInput; System.out.print("Press the ENTER key to toss the dice."); keyIn.nextLine(); int tries = 0; int sum = 0; while (sum != 7 &amp;&amp; sum != 11) { // Here is where you call your newly created method int roll1 = rollDice(); int roll2 = rollDice(); sum = roll1 + roll2; System.out.println(roll1 + " + " + roll2 + " = " + sum); tries++; } } </code></pre> <p>The idea is that you want to split up a complicated task into many smaller ones. This way it makes it much easier to debug. The above is just an example, but if you are performing an operation that you realise is repetitive, a function can never hurt.</p> <p>Try to think about your function in the following way: </p> <p><strong>1. What does my function do?</strong></p> <p><strong>2. What data should it provide me with?</strong></p> <p><strong>3. What is the minimum my function requires to provide me with this data?</strong></p> <p>As for a function that counts the characters for a string as mentioned in the comments:</p> <ol> <li>Your function counts the characters in a string. </li> <li>The data that it provides you with is simply a number. </li> <li>All you need to get this number is a string.</li> </ol> <p>Given this information, we can come up with the following function protocol:</p> <pre><code>public static int countCharacters(String myString) { int count = myString.length(); return count; } </code></pre> <p>The return type and value is an <code>int</code> as this is what it needs to provide you with, and <code>myString</code> is the only data the function needs to work. Thinking this way makes code much more maintainable, and you will be able to break up a complicated task into several very simple steps.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload