Skip to the content.

1.6 Compound Assignment Operators Homework

Popcorn Hack #1


Transform this beginner code into more advanced code using compound assignment operators.

int playerScore = 1000;
int playerHealth = 100;
int enemiesDefeated = 0;

// Player defeats an enemy worth 250 points
playerScore += 250;

// Player takes 15 damage
playerHealth -= 15;

// Enemy count goes up
enemiesDefeated ++;

// Boss battle: double the current score!
playerScore *= 2;

// Healing potion restores health to 80% of current
playerHealth *= 4;
playerHealth /= 5;  // 4/5 = 0.8, but we need integer math

System.out.println("Score: " + playerScore);

Popcorn Hack #2


Write a short program where a variable called score starts at 100. Use at least three different compound assignment operators to update score, and print the result after each step.

int score = 100;
score -= 10; //sub 10
score *=23; // multiply by 23
score /=7; //divide 7

System.out.println("Score: " + score);

Homework


Simulate managing a personal bank account over time:

Suggested variables to track: balance - Current account balance transactions - Number of transactions made monthlyFee - Account maintenance costs interestRate - Interest earned/applied


int balance = 1000000;
System.out.println("Your current balance is: " + balance);

balance -= 50000; // withdraw 50,000
System.out.println("You withdrew: " + 50000);
System.out.println("Your current balance after withdrawl: " + balance);

balance += 10000; // deposit 10,000
System.out.println("You deposited: " + 10000);
System.out.println("Your current balance after deposit: " + balance);

balance *= 1.05; //  5% interest
System.out.println("You earned 5% interest");
System.out.println("Your current balance after interest: " + balance);