Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Solved problems in TorpedoStore.java #1

Merged
merged 2 commits into from
Oct 16, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 15 additions & 13 deletions src/main/java/hu/bme/mit/spaceship/TorpedoStore.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,23 @@
import java.util.Random;

/**
* Class storing and managing the torpedoes of a ship
*
* (Deliberately contains bugs.)
*/
* Class storing and managing the torpedoes of a ship
*
* (Deliberately contains bugs.)
*/
public class TorpedoStore {

// rate of failing to fire torpedos [0.0, 1.0]
private double FAILURE_RATE = 0.0; //NOSONAR
private double FAILURE_RATE = 0.0; // NOSONAR

private int torpedoCount = 0;

public TorpedoStore(int numberOfTorpedos){
public TorpedoStore(int numberOfTorpedos) {
this.torpedoCount = numberOfTorpedos;

// update failure rate if it was specified in an environment variable
String failureEnv = System.getenv("IVT_RATE");
if (failureEnv != null){
if (failureEnv != null) {
try {
FAILURE_RATE = Double.parseDouble(failureEnv);
} catch (NumberFormatException nfe) {
Expand All @@ -28,20 +28,22 @@ public TorpedoStore(int numberOfTorpedos){
}
}

public boolean fire(int numberOfTorpedos){
if(numberOfTorpedos < 1 || numberOfTorpedos > this.torpedoCount){
new IllegalArgumentException("numberOfTorpedos");
Random generator = new Random();

public boolean fire(int numberOfTorpedos) {
if (numberOfTorpedos < 1 || numberOfTorpedos > this.torpedoCount) {
throw new IllegalArgumentException("numberOfTorpedos");
}

boolean success = false;

// simulate random overheating of the launcher bay which prevents firing
Random generator = new Random();

double r = generator.nextDouble();

if (r >= FAILURE_RATE) {
// successful firing
this.torpedoCount =- numberOfTorpedos;
this.torpedoCount -= numberOfTorpedos;
success = true;
} else {
// simulated failure
Expand All @@ -51,7 +53,7 @@ public boolean fire(int numberOfTorpedos){
return success;
}

public boolean isEmpty(){
public boolean isEmpty() {
return this.torpedoCount <= 0;
}

Expand Down
Loading