Simulazione Verifica
This commit is contained in:
73
SimulazioneVerifica/src/Main.java
Normal file
73
SimulazioneVerifica/src/Main.java
Normal file
@@ -0,0 +1,73 @@
|
||||
class SensorException extends Exception {
|
||||
SensorException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
interface Readable {
|
||||
double readValue() throws SensorException;
|
||||
}
|
||||
|
||||
abstract class Sensor implements Readable {
|
||||
private String id;
|
||||
Sensor(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
String getId() {
|
||||
return id;
|
||||
}
|
||||
@Override
|
||||
public abstract double readValue() throws SensorException;
|
||||
}
|
||||
|
||||
class TemperatureSensor extends Sensor {
|
||||
TemperatureSensor(String id) {
|
||||
super(id);
|
||||
}
|
||||
@Override
|
||||
public double readValue() throws SensorException {
|
||||
if (Math.random() < 0.1) {
|
||||
throw new SensorException("Errore di lettura temperatura");
|
||||
}
|
||||
return 18 + Math.random() * 8;
|
||||
}
|
||||
}
|
||||
|
||||
class HumiditySensor extends Sensor {
|
||||
HumiditySensor(String id) {
|
||||
super(id);
|
||||
}
|
||||
@Override
|
||||
public double readValue() throws SensorException {
|
||||
if (Math.random() < 0.1) {
|
||||
throw new SensorException("Errore di lettura umidità");
|
||||
}
|
||||
return 30 + Math.random() * 40;
|
||||
}
|
||||
}
|
||||
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
Sensor[][] grid = new Sensor[3][3];
|
||||
for (int i = 0; i < grid.length; i++) {
|
||||
for (int j = 0; j < grid[i].length; j++) {
|
||||
String id = "S" + i + j;
|
||||
if ((i + j) % 2 == 0)
|
||||
grid[i][j] = new TemperatureSensor(id);
|
||||
else
|
||||
grid[i][j] = new HumiditySensor(id);
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < grid.length; i++) {
|
||||
for (int j = 0; j < grid[i].length; j++) {
|
||||
try {
|
||||
double value = grid[i][j].readValue();
|
||||
System.out.printf("Sensore %s: %.2f%n", grid[i][j].getId(), value);
|
||||
} catch (SensorException e) {
|
||||
System.out.printf("Errore nel sensore %s: %s%n",
|
||||
grid[i][j].getId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user