POO TP3 added

This commit is contained in:
TiagoRG 2023-02-27 16:08:45 +00:00
parent c94006cba8
commit 4ad0baa51c
2 changed files with 134 additions and 0 deletions

View File

@ -0,0 +1,66 @@
package tp_codecheck.tp03;
/**
A simulated traffic light.
*/
public class TrafficLight1
{
private String color;
private int reds;
/**
Constructs a green traffic light.
*/
public TrafficLight1()
{
this.color = "green";
this.reds = 0;
}
/**
Constructs a traffic light.
@param initialColor the initial color "green", "yellow", or "red"
*/
public TrafficLight1(String initialColor)
{
this.color = initialColor;
this.reds = initialColor == "red" ? 1 : 0;
}
/**
Moves this traffic light to the next color.
*/
public void next()
{
switch (this.color) {
case "red":
this.color = "green";
break;
case "green":
this.color = "yellow";
break;
case "yellow":
this.color = "red";
this.reds += 1;
break;
}
}
/**
Returns the current color of this traffic light.
@return the current color
*/
public String getColor()
{
return this.color;
}
/**
Counts how often this traffic light has been red.
@return the number of times this traffic light has been red
*/
public int getReds()
{
return this.reds;
}
}

View File

@ -0,0 +1,68 @@
package tp_codecheck.tp03;
/**
A simulated traffic light.
*/
public class TrafficLight2
{
private int steps;
/**
Constructs a green traffic light.
*/
public TrafficLight2()
{
this.steps = 0;
}
/**
Constructs a traffic light.
@param initialColor the initial color "green", "yellow", or "red"
*/
public TrafficLight2(String initialColor)
{
switch (initialColor) {
case "green":
this.steps = 0;
break;
case "yellow":
this.steps = 1;
break;
case "red":
this.steps = 2;
break;
}
}
/**
Moves this traffic light to the next color.
*/
public void next()
{
steps++;
}
/**
Returns the current color of this traffic light.
@return the current color
*/
public String getColor()
{
int rem = (this.steps + 1) % 3;
if (rem == 0)
return "red";
else if (rem == 1)
return "green";
else
return "yellow";
}
/**
Counts how often this traffic light has been red.
@return the number of times this traffic light has been red
*/
public int getReds()
{
return (this.steps + 1) / 3;
}
}