I tried different ways, but the outcome is still not the way it should be. I have to create a small weather app in Kotlin with some Design Patterns.
interface Sensor {
fun getTemperature() : Float
}
class RandomSensor () : Sensor {
override fun getTemperature(): Float {
var randomTemp : Double = Random.nextDouble (0.0, 40.00)
return randomTemp.toFloat()
}
}
class Thermometer (var sensor: Sensor) {
var newTemp = this.sensor.getTemperature()
val tempwerte = mutableListOf<Float>(newTemp)
val observers = mutableListOf<TemperaturObserver>()
fun register(observer:TemperaturObserver) {
observers.add(observer)
}
fun remove(observer: TemperaturObserver) {
observers.remove(observer)
}
fun dataChanged() {
observers.forEach {it.update(newTemp)}
}
fun messen() {
var n = 100
for (i in 0 until n) {
newTemp = this.sensor.getTemperature()
if(i != n) {
dataChanged()
tempwerte.add(newTemp)
}
}
}
fun getTenlastItems () = tempwerte.takeLast(10)
fun getHundredItems () = tempwerte.take (100)
the observer "weatherReport" should collect 10 items (temperature), print them and collect the next 10 items and so on
My solution
interface TemperaturObserver {
fun update (newTemp : Float)
}
class WeatherReport (private var station : Thermometer) : TemperaturObserver {
override fun update (newTemp: Float) {
var newList = mutableListOf<Float>(newTemp)
while (newList.size != 10) {
newList.add(newTemp)
}
println(newList)
}
}
creates this output
[40.0, 40.0, 40.0, 40.0, 40.0, 40.0, 40.0, 40.0, 40.0, 40.0]
[24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0, 24.0]
etc....
Any ideas how to solve the problem? It should be like that:
[21.0, 23.0, 0.0, 1.0, 35.0, 4.0, 14.0, 3.0, 16.0, 36.0]
[22.0, 27.0, 21.0, 32.0, 20.0, 31.0, 37.0, 33.0, 24.0, 2.0]
etc...
Thanks!
Aucun commentaire:
Enregistrer un commentaire