Veritas Curat
Veritas Curat

Reputation: 25

Populating a class in Kotlin with user input

I am brand new to Kotlin and am taking a Mobile App Development course. In this project we're trying to create a class and populate the information with a user input. I've followed with the book as far as creating the class but Im having issues filling it.

The way I'm thinking it should process would be: Class creation call a GetStudentInfo function information filled out and then returned back

But I cannot for the life of my figure this out. My text book only has creating classes and populating with static information. Nothing relating to user input.

Thank you so much for the help.


class Student
{
    var FName: String?=null
    var LName: String?=null
    var Street_Add: String?=null
    var City: String?=null
    var State: String?=null
    var Zip: Int?=null
    var GPA: Double?=null
    var Major: String?=null

}

fun main(args: Array<String>) {
GetStudentInfo()
    var StudentInfo = Student()

    println(StudentInfo.FName)
}

fun GetStudentInfo()
{
    var StudentInfo = Student()
    print("Please enter the student's first name: ")
    StudentInfo.FName = readLine()

Upvotes: 0

Views: 715

Answers (1)

Y.Kakdas
Y.Kakdas

Reputation: 843

You may use kotlin.io readLine as you have tried. You just need to cast what you need. If you want to take Double just do val value = readLine().toDouble() You can also create functions for simplicity such as,

fun readInt() = readLine()!!.toInt()

Or, you may use legacy scanner way.

 with(Scanner(System.`in`)){
      print("Please enter the student's first name: ")
      StudentInfo.FName = nextLine()
 }

EDIT: (Sample Program)

fun main() {
    val studentInfo = getStudentInfo()
    println(studentInfo)
}

fun getStudentInfo(): Student {
    val student = Student()
    return student.apply {
        print("Please enter the student's first name: ")
        FName = readLine()
        print("Please enter the student's last name: ")
        LName = readLine()
        print("Please enter the student's street add: ")
        Street_Add = readLine()
        print("Please enter the student's city: ")
        City = readLine()
        print("Please enter the student's state: ")
        State = readLine()
        print("Please enter the student's zip: ")
        Zip = readLine()?.toInt()
        print("Please enter the student's gpa: ")
        GPA = readLine()?.toDouble()
        print("Please enter the student's major: ")
        Major = readLine()
    }
}

data class Student(
    var FName: String? = null,
    var LName: String? = null,
    var Street_Add: String? = null,
    var City: String? = null,
    var State: String? = null,
    var Zip: Int? = null,
    var GPA: Double? = null,
    var Major: String? = null
)

Upvotes: 2

Related Questions