Advertisement
fannyxmikasa

add/delete student

Nov 10th, 2020
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.69 KB | None | 0 0
  1. import java.util.Scanner
  2. import kotlin.system.exitProcess
  3.  
  4. val scanner = Scanner(System.`in`)
  5.  
  6. class Program1{
  7.     var studentName: MutableList<String> = ArrayList()  //don't make it private so we can access it in main function
  8.     fun addStudent(){
  9.         print("\nEnter student name: ")
  10.         val name = readLine()!!
  11.         studentName.add(name)
  12.     }
  13.     fun deleteStudent(){
  14.         val result = studentName.toMutableList()
  15.          /*if student in list is 1 and
  16.           *when delete function is called it automatically removes the only student in list
  17.           *without giving the specific index
  18.           */
  19.         studentName = if(studentName.size == 1) {
  20.             result.removeAt(0)
  21.             result
  22.         } else {
  23.             print("Enter index to delete: ")
  24.             val index = scanner.nextInt()
  25.             result.removeAt(index)
  26.             result
  27.         }
  28.     }
  29.     fun displayStudent(){
  30.             println("List of students: ")
  31.             var index = 0
  32.             for (name in studentName) {
  33.                 println("[$index]$name")
  34.                 index += 1
  35.             }
  36.     }
  37. }
  38. fun main(){
  39.     val call = Program1()
  40.     while(true){
  41.     println("\n[1]Add Student [2]Delete Student [3] Display All Student [Other Key]Exit ")
  42.     print("Answer: ")
  43.  
  44.         when (scanner.next().single()) {
  45.             '1' -> call.addStudent()
  46.             '2' -> if(call.studentName.isNotEmpty()){call.deleteStudent()} else println("No student in list")
  47.             '3' -> if(call.studentName.isNotEmpty()){call.displayStudent()} else println("No student in list")
  48.             else -> exitProcess(0) //break the infinite loop (exit app)
  49.         }
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement