Simulazione Verifica

This commit is contained in:
2025-10-16 08:43:10 +02:00
parent 9099666b07
commit c1f2c32bd7
3 changed files with 111 additions and 0 deletions

View 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());
}
}
}
}
}