0
Age Groups
Hello, my code is correct in all test runs except test run Number 4. Sadly I cannot see which number was tested. Could someone please give me a hint. fun main(args: Array<String>) { var age = readLine()!!.toInt() var x = when { age >0 && age <12 -> "Child" age <18 -> "Teen" age <65 -> "Adult" age >=65 -> "Senior" else -> "Invalid age" } println(x) }
4 Respuestas
+ 5
Denis Durban not sure where x came from and it is not defined from what I see.
If x is suppose to equal the string of child teen adult senior and invalid x was not declared as string ...
"IF" you go from oldest to youngest category this would be the easiest given that 65 and older are seniors
And 0 and upto 11 are child(ren)
And anything below 0 are treated as "invalid"
If you go from youngest to oldest then you pretty much end up using age is greater than or equal to ( && ) less than as if you are using if, else if, else (conditions)
fun main(args: Array<String>){
var age = readLine()!!.toInt()
when {
age>65 -> println("Senior")
age>17 -> println("Adult")
age>11 -> println("Teen")
age>=0 -> println("Child")
else -> println("Invalid age")}
}
+ 4
Maybe a newborn with age of 0 can be qualified as "Child" but your program considers it invalid. I cannot think of another possible flaw.
+ 2
I think in last condition you use age<65->"Adult"
age>=65->"Senior"
When you print age is greater than 65 then when the block will stop? if the the user enter 86,78 ..etc then it prints senior
If you want to print else block then you should write like this:-
age<=100->"Senior"
Now, if the user want to age print is greater than 100 then it will show "Invalid age", hope you understand what I mean to say.
+ 2
Thanks everyone ~ I'll try it.