Lesson 4 - Activity 1 - Can you use integers and variables?

Time: 15 minutes

Purpose: This activity helps you get familiar with using integer operators

Introduction: You’ve seen how to add two integer numbers together - do you think you can try a few other operations on your own?

Task: Perform the following operations on integer variables and print the results,

  1. Divide one integer by another
  2. Subtract one integer from another
  3. Multiply one integer by another
  4. Get the modulus of one integer from another

Sorry, I got carried away with this one :wink:

    // Divide one integer by another

    int numPersons = 181, applesPerPerson;
    applesPerPerson = numApples / numPersons;
    System.out.println("If we have " + numPersons + " persons who want apples, then we have " + applesPerPerson + " apples for each person.");

    // Multiply one integer by another

    int totalApplesTaken, totalFruitsAfterEatingApples;
    totalApplesTaken = applesPerPerson * numPersons;

    // Subtract one integer from another

    totalFruitsAfterEatingApples = TotalFruits - totalApplesTaken;

    System.out.println("After taking the " + totalApplesTaken + " apples, we have " +  totalFruitsAfterEatingApples + " fruities left.");

    // Get the modulus of one integer from another

    int numPersonsModulus = 191, numApplesLeftOver;
    String strApples = "apples", strApplesLeftOver = "apples", strPersons = "persons", strApplesPerPerson = "apples";

    applesPerPerson = numApples / numPersonsModulus;
    numApplesLeftOver = numApples % numPersonsModulus;

    if (numPersonsModulus == 1){
        strPersons = "person";
    }
    if (numApplesLeftOver == 1){
        strApplesLeftOver = "apple";
    }

    if (applesPerPerson == 1){
        strApplesPerPerson = "apple";
    }

    System.out.println(HandyStuffLib.newLine + "But wait... " + HandyStuffLib.newLine + HandyStuffLib.newLine + "What if we have " + numPersonsModulus + " " + strPersons + "?");
    System.out.println("Then we have " + applesPerPerson + " " + strApplesPerPerson + " per person! " + HandyStuffLib.newLine + "And there will be " + numApplesLeftOver + " " + strApplesLeftOver + " leftover.");

You crazy man - you went all in! You looked to be having a lot of fun.

1 Like