Bird
0
0

Given a class Player with private int 'health' and method 'TakeDamage(int amount)', which of these implementations correctly reduces health but never below zero?

hard🚀 Application Q9 of 15
C Sharp (C#) - Classes and Objects
Given a class Player with private int 'health' and method 'TakeDamage(int amount)', which of these implementations correctly reduces health but never below zero?
Apublic void TakeDamage(int amount) { if (amount > 0) health -= amount; }
Bpublic void TakeDamage(int amount) { health -= amount; if (health < 0) health = 0; }
Cpublic void TakeDamage(int amount) { health = health - amount; }
Dpublic void TakeDamage(int amount) { health = Math.Max(health, amount); }
Step-by-Step Solution
Solution:
  1. Step 1: Understand health reduction logic

    Health should decrease by amount but not go below zero.
  2. Step 2: Check each option's logic

    public void TakeDamage(int amount) { health -= amount; if (health < 0) health = 0; } subtracts amount then sets health to zero if negative, correctly preventing negative health.
  3. Final Answer:

    public void TakeDamage(int amount) { health -= amount; if (health < 0) health = 0; } -> Option B
  4. Quick Check:

    Health never below zero with check after subtraction [OK]
Quick Trick: Clamp health to zero after damage [OK]
Common Mistakes:
MISTAKES
  • Not preventing health from going negative
  • Using wrong comparison operators
  • Assigning health incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes