HashMap I implemented HashMap with kotlin. id is key and name is value
maptest.kt
import java.util.Scanner
import java.util.InputMismatchException
var map = kotlin.collections.HashMap<Int , String>()
fun main(arg : Array<String>) {
val input = Scanner(System.`in`)
var i : Int
try {
loop@ while(true) {
println("What are you doing?\n" +
"input=>1" + "display=>2" + "look for=>3" + "Delete=>4"+ "End=>5")
i = input.nextInt()
when (i) {
1 -> {
Scan()
}
2 -> {
println(map)
}
3 -> {
search()
}
4 -> {
delete()
}
5->{
break@loop
}
}
}
}catch(e : InputMismatchException){
println("The type is different: " +e)
}
}
map.kt
import java.util.*
val input = Scanner(System.`in`)
fun search(){
val key : Int
println("Please enter id")
try {
key = input.nextInt()
if (map.containsKey(key)) {
println("$key =" + map.get(key))
} else {
println("That id does not exist")
}
}catch (e : InputMismatchException){
println("The type is different: ")
}
}
fun Scan(){
println("Please enter your name")
val name = input.next()
println("Please enter id")
val key : Int = input.nextInt()
try {
if (map.containsKey(key)) {
println("Do you want to overwrite?\n" +
"Yes=>1 No=>2")
when (input.nextInt()) {
1 -> {
map.put(key, name)
}
2 -> {
}
}
} else {
map.put(key, name)
}
}
catch (e : InputMismatchException){
println("The type is different: ")
}
}
fun delete() {
println("Delete all=>1 1 Delete data=>2 Cancel=>3")
try {
when (input.nextInt()) {
1 -> {
map.clear()
}
2 -> {
println("Please enter the id to delete")
val keyid: Int = input.nextInt()
map.remove(keyid)
}
3 -> {
}
}
}catch (e : InputMismatchException){
println("The type is different: ")
}
}
The implementation such as inputting the name in Japanese and retrying is coming again.
Recommended Posts