How to resolve the algorithm Simple database step by step in the Kotlin programming language
How to resolve the algorithm Simple database step by step in the Kotlin programming language
Table of Contents
Problem Statement
Write a simple tool to track a small set of data. The tool should have a command-line interface to enter at least two different values. The entered data should be stored in a structured format and saved to disk. It does not matter what kind of data is being tracked. It could be a collection (CDs, coins, baseball cards, books), a diary, an electronic organizer (birthdays/anniversaries/phone numbers/addresses), etc.
You should track the following details:
The command should support the following Command-line arguments to run:
The category may be realized as a tag or as structure (by making all entries in that category subitems) The file format on disk should be human readable, but it need not be standardized. A natively available format that doesn't need an external library is preferred. Avoid developing your own format if you can use an already existing one. If there is no existing format available, pick one of:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Simple database step by step in the Kotlin programming language
The above source code in Kotlin is a simple database application that allows you to add items to a database, print the latest added item(s), or print all items in the database. The database is stored in a CSV file simdb.csv
.
The program first checks if the simdb.csv
file exists and creates it if it doesn't. Then, it checks the first argument of the program to determine which action to perform:
-
If the first argument is "add", the program checks if the number of arguments is at least 2. If not, it prints a usage message and exits. Otherwise, it creates a new
Item
object with the given name, date, and category, and stores it in the database. -
If the first argument is "latest", the program checks if the number of arguments is at least 1. If not, it prints a usage message and exits. Otherwise, it loads the database, and prints the latest added item(s). If a category is specified, it only prints the latest item(s) in that category.
-
If the first argument is "all", the program loads the database and prints all the items in the database.
Finally, if the first argument is not one of the above, the program prints a usage message and exits.
The program uses a SimpleDateFormat
object to format the date of each item. It also uses a Comparable
interface to allow the items to be sorted by date.
The program is written in a modular way, with each function performing a specific task. This makes the program easier to read and maintain.
Source code in the kotlin programming language
// version 1.2.31
import java.text.SimpleDateFormat
import java.util.Date
import java.io.File
import java.io.IOException
val file = File("simdb.csv")
class Item(
val name: String,
val date: String,
val category: String
) : Comparable<Item> {
override fun compareTo(other: Item) = date.compareTo(other.date)
override fun toString() = "$name, $date, $category"
}
fun addItem(input: Array<String>) {
if (input.size < 2) {
printUsage()
return
}
val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
val date = sdf.format(Date())
val cat = if (input.size == 3) input[2] else "none"
store(Item(input[1], date, cat))
}
fun printLatest(a: Array<String>) {
val db = load()
if (db.isEmpty()) {
println("No entries in database.")
return
}
// no need to sort db as items are added chronologically
if (a.size == 2) {
var found = false
for (item in db.reversed()) {
if (item.category == a[1]) {
println(item)
found = true
break
}
}
if (!found) println("There are no items for category '${a[1]}'")
}
else println(db[db.lastIndex])
}
fun printAll() {
val db = load()
if (db.isEmpty()) {
println("No entries in database.")
return
}
// no need to sort db as items are added chronologically
for (item in db) println(item)
}
fun load(): MutableList<Item> {
val db = mutableListOf<Item>()
try {
file.forEachLine { line ->
val item = line.split(", ")
db.add(Item(item[0], item[1], item[2]))
}
}
catch (e: IOException) {
println(e)
System.exit(1)
}
return db
}
fun store(item: Item) {
try {
file.appendText("$item\n")
}
catch (e: IOException) {
println(e)
}
}
fun printUsage() {
println("""
|Usage:
| simdb cmd [categoryName]
| add add item, followed by optional category
| latest print last added item(s), followed by optional category
| all print all
| For instance: add "some item name" "some category name"
""".trimMargin())
}
fun main(args: Array<String>) {
if (args.size !in 1..3) {
printUsage()
return
}
file.createNewFile() // create file if it doesn't already exist
when (args[0].toLowerCase()) {
"add" -> addItem(args)
"latest" -> printLatest(args)
"all" -> printAll()
else -> printUsage()
}
}
You may also check:How to resolve the algorithm Assertions step by step in the Zig programming language
You may also check:How to resolve the algorithm Greatest common divisor step by step in the TSE SAL programming language
You may also check:How to resolve the algorithm Array length step by step in the S-BASIC programming language
You may also check:How to resolve the algorithm Primality by trial division step by step in the AppleScript programming language
You may also check:How to resolve the algorithm Circles of given radius through two points step by step in the Java programming language