0

this is my code:

import java.util.*

open class Food(private var calories: Long) : Comparable<Food> {
//    override fun compareTo(other: Food): Int {
//        return if(this.calories==other.calories)
//            0
//        else if(this.calories>other.calories)
//            +1
//        else -1
//    }
    override fun toString(): String {
        return "calories=$calories"
    }
//    override fun compareTo(other: Food)=compareValuesBy(this, other,
//            { it.calories },
//            { it.calories }
//        )
}


class Flafel():Food(100){
    override fun toString(): String {
        return "Flafel ${super.toString()}"
    }
}
class Pizza():Food(200){
    override fun toString(): String {
        return "Pizza ${super.toString()}"
    }
}
class Hamburger():Food(300){
    override fun toString(): String {
        return "Hamburger ${super.toString()}"
    }
}

class Restaurant {
    val foodList = Array<Food?>(10) {null}
    init {

        for (i in 0 until foodList.size-1) {
            var newObject=when((1..3).random()){
                1->Flafel()
                2->Pizza()
                else->Hamburger()
            }
            foodList[i]=newObject
        }
        Arrays.sort(foodList)
        for (i in 0 until foodList.size-1) {
            println(foodList[i])
        }
    }
}
fun main() {
    var lobsterRestaurant=Restaurant()
}

I have tried two kind of code (which is commented in the code) but I get this exception:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Comparable.compareTo(Object)" because "pivot" is null at java.base/java.util.ComparableTimSort.binarySort(ComparableTimSort.java:262) at java.base/java.util.ComparableTimSort.sort(ComparableTimSort.java:189) at java.base/java.util.Arrays.sort(Arrays.java:1041) at Restaurant.(Main.kt:50) at MainKt.main(Main.kt:57) at MainKt.main(Main.kt)

GhostCat
  • 137,827
  • 25
  • 176
  • 248
Zarisa
  • 13
  • 6
  • 2
    Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – DontKnowMuchBut Getting Better Feb 01 '22 at 19:33
  • 2
    I don't know Kotlin enough, but this maybe wrong `Array(10) {null}` and you get a null elemet in `foodList`. – PeterMmm Feb 01 '22 at 19:34

1 Answers1

1

Problem is in this part of code:

for (i in 0 until foodList.size-1)

You leave the last 10th element of array unfilled an it stays null, so it causes an NPE. If you would do it like that then it would work:

for (i in 0 until foodList.size)

Thats because until does not include the last number in the range.

Tarmo
  • 3,851
  • 2
  • 24
  • 41