-
Notifications
You must be signed in to change notification settings - Fork 714
/
Copy pathBaseMenu.kt
81 lines (68 loc) · 2.01 KB
/
BaseMenu.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package Menu
import java.util.Scanner
import Item.Item
class BaseMenuItem(
val name: String,
val action: ()-> Unit
)
abstract class BaseMenu<T: Item> (
open val items: MutableList<T>,
open val greeting: String,
open val createActionName: String
) {
private val scan = Scanner(System.`in`)
private var getInputValue = false
fun start() {
greeting()
while (!getInputValue) {
val menuItems = menuItems()
printMenu(menuItems)
correctRange()
if (scan.hasNextInt()) {
val index = scan.nextInt()
if (index > menuItems.lastIndex) {
println("Такого варианта нет. Выбирете из вариантов ниже:")
} else {
menuItems[index].action()
}
} else {
println("Неверный ввод!")
scan.next()
}
}
}
private fun greeting() {
println(greeting)
}
private fun correctRange() {
println("Введите цифру от 0 до " + (items.lastIndex + 2).toString())
}
private fun printMenu(menuItems: List<BaseMenuItem>) {
menuItems.forEach {
println(menuItems.indexOf(it).toString() + ". " + it.name)
}
}
abstract fun createItem(): T
abstract fun actionForSelectedItem(item: T)
private fun menuItems(): List<BaseMenuItem> {
val menuItems:MutableList<BaseMenuItem> = mutableListOf(
BaseMenuItem(createActionName, {
var item = createItem()
this.items.add(item)
})
)
items.forEach {it
menuItems.add(
BaseMenuItem(it.name, {
actionForSelectedItem(it)
})
)
}
menuItems.add(
BaseMenuItem("Выйти", {
this.getInputValue = true
})
)
return menuItems
}
}