Grade book program comparing test scores - kotlin

I have a gradebook, given two maps of test scores, update the students' grades only if they did better on the second exam. Now i need to enter second test scores into terminal and get final total from 2 tests. My problem is that i can only initialize score, but i need it in terminal. How can i do this?
class student{
lateinit var testScore: Any
var testScores: Int = 100
}
import java.util.*
fun main() {
val Andrew = student()
val Tom = student()
val Tobey = student()
Andrew.testScores = 67
print("Andrew's test score ")
println(Andrew.testScores)
Tom.testScores = 65
print("Tom's test score ")
println(Tom.testScores)
Tobey.testScores = 76
print("Tobey's test score ")
println(Tobey.testScores)
var input: String
var score1: Double
var score2: Double
var score3: Double
var repeat: Char
val keyboard = Scanner(System.`in`)
println(
"Enter second test's scores "
)
if(Andrew.testScores < score1){
var valid = false
Andrew.testScores = score1.toInt()
}
if(Tom.testScores < score2){
Tom.testScores = score2.toInt()
}
if(Tobey.testScores < score3){
Tobey.testScores = score3.toInt()
}
print("Andrew's test score ${Andrew.testScores} ")
print("Tom's test score ${Tom.testScores} ")
print("Tobey's test score ${Tobey.testScores} ")
do {
print("Enter score #1: ")
score1 = keyboard.nextDouble()
print("Enter score #2: ")
score2 = keyboard.nextDouble()
print("Enter score #3: ")
score3 = keyboard.nextDouble()
println(
("Would you enter new scores?")
)
print("Enter Y for yes or N for no: ")
input = keyboard.next()
repeat = input[0]
} while (repeat == 'Y' || repeat == 'y')
}

Related

Kotlin: I am unable to hold previous value of a function when calling it multiple times

I need to show different seat arrangement till the user is making choices and register it's previous choices as well in the displayed seat arrangement.
My code is:
package cinema
fun main() {
println("Enter the number of rows:")
val row = readLine()!!.toInt()
println("Enter the number of seats in each row")
val seats = readLine()!!.toInt()
var price = 0
val totalSeats = row*seats
var rowNumberUpdate = 0
var seatNumberUpdate = 0
var a = true
fun seatDisplay(){
var newSeatCount = 1
println("Cinema: ")
print(" ")
while(newSeatCount <=seats){
print(" $newSeatCount")
newSeatCount += 1
}
print("\n")
for(i in 1..row){
print(i)
for(j in 1..seats){
if(i == rowNumberUpdate && j==seatNumberUpdate) print(" B") else print(" S")
}
println()
}
}
fun priceDisplay(){
println("Enter a row number: ")
val rowNumber = readln().toInt()
rowNumberUpdate = rowNumber
println("Enter a seat number in that row: ")
val seatNumber = readln().toInt()
seatNumberUpdate = seatNumber
if(totalSeats<=60){
price = 10
} else {
if(row%2==0){
if(rowNumber<=row/2) price = 10 else price = 8
} else {
if(rowNumber<=row/2) price = 10 else price = 8
}
}
println("Ticket price: $$price")
}
while(a){
println("1. Show the seats")
println("2. Buy a ticket")
println("0. Exit")
val optionsInput = readln().toInt()
when(optionsInput){
1 -> seatDisplay()
2 -> priceDisplay()
0 -> a = false
}
}
}
Problem with this code is, everytime user is making choice it is showing the seat arrangement as per the latest choice. It doesn't hold the value of previous choices.
You can see this in output attached as an image. Please zoom the image for clear visibility.
Hoping to get some help from the community.
You store the selection of the user in variables rowNumberUpdate and seatNumberUpdate that can hold singular values. If you intend to memorize all choices, you have to change these variables to be some kind of collection (e.g. a list) and add every choice to that collection:
val seatUpdate = mutableListOf<Pair<Int, Int>>()
and in seatDisplay:
if(seatUpdate.contains(Pair(i,j))) print(" B") else print(" S")
and in priceDisplay:
seatUpdate.add(Pair(rowNumber, seatNumber))

Why doesn't this While loop work as intended?

Hey guys, newbie here. One question, can't understand why this while loop doesn't work even when I entered a int bigger than 9 to the variable num, the while loop should repeat itself until the expression is false, and it doesn't, no output even. Am I missing something here? Thanks in advance.
fun main () {
while(true) {
println ("\nWrite a positive number: ")
var num = readLine()!!.toInt()
var sum = 0
if (num > 9) {
while (num > 9) {
var digit = num % 10
sum = sum + digit
num = num / 10
}
println("\nDigit Sum: $sum")
} else if (num in 1..9) {
println("\nDigit Sum for the number $num is $num")
} else {
println("\nInvalid input, try again.")
}
}
}
The issue is that you are not summing the last num when it gets less or equal to 9. You can even simplify your code a bit. Try the following:
fun main() {
while(true) {
println ("\nWrite a positive number: ")
val insertedNumber = readLine()!!.toInt()
var num = insertedNumber
var sum = 0
while (num > 9) {
val digit = num % 10
sum = sum + digit
num = num / 10
}
sum = sum + num
println("\nDigit Sum for the number $insertedNumber is $sum")
}
}
You don't need to redeclare the variables every time
var sum = sum + digit
var num = num / 10
So simply remove var
sum = sum + digit
num = num / 10

Read a sequence of numbers of undefined size & print the largest number & position of its first occurrence

I need to read a sequence of numbers of undefined size & prints the largest number & the position of its first occurrence
Can anyone help with this code:
import java.util.Scanner
fun main() {
val scan = Scanner(System.`in`)
val num = scan.nextInt()
var max = Int.MIN_VALUE
var pos = 0
var i = 1
do {
if (max < num) {
max = num
pos = i
}
i++
} while (scan.hasNext())
print("$max $pos")
}
You just need to read a new number in each iteration:
import java.util.Scanner
fun main() {
val scan = Scanner(System.`in`)
var max = Int.MIN_VALUE
var pos = 0
var i = 1
while (scan.hasNext()) {
// Read a new number here
val num = scan.nextInt()
if (max < num) {
max = num
pos = i
}
i++
}
print("$max $pos")
}
My solution to this task
This is a simple task, it can be solved in a simple way without using a “java.util.Scanner”. You just need to read a new number in each iteration.
fun main() {
var pos = 0
var max = 0
var count = 1
while (true) {
val input = readlnOrNull()
if (input == null) break
val num = input.toInt()
if (pos == 0 || num > max) {
max = num
pos = count
}
count++
}
print("$max $pos")
}

Kotlin - The caracter literal does not conform expect type Int

I'm struggling with types with my program, I've been asked to do it in JS first and it worked fine but now I can't achieve the result.
Do you think I should make another 'algorithm' ? In advance, thank you for your time.
fun main(){
// the idea is to put numbers in a box
// that cant be larger than 10
val data = "12493419133"
var result = data[0]
var currentBox = Character.getNumericValue(data[0])
var i = 1
while(i < data.length){
val currentArticle = Character.getNumericValue(data[i])
currentBox += currentArticle
println(currentBox)
if(currentBox <= 10){
result += Character.getNumericValue(currentArticle)
}else{
result += '/'
//var resultChar = result.toChar()
// result += '/'
currentBox = Character.getNumericValue(currentArticle)
result += currentArticle
}
i++
}
print(result) //should print 124/9/341/91/33
}
The result is actually of a Char type, and the overload operator function + only accepts Int to increment ASCII value to get new Char.
public operator fun plus(other: Int): Char
In idomatic Kotlin way, you can solve your problem:
fun main() {
val data = "12493419133"
var counter = 0
val result = data.asSequence()
.map(Character::getNumericValue)
.map { c ->
counter += c
if (counter <= 10) c.toString() else "/$c".also{ counter = c }
}
.joinToString("") // terminal operation, will trigger the map functions
println(result)
}
Edit: If the data is too large, you may want to use StringBuilder because it doesn't create string every single time the character is iterated, and instead of using a counter of yourself you can use list.fold()
fun main() {
val data = "12493419133"
val sb = StringBuilder()
data.fold(0) { acc, c ->
val num = Character.getNumericValue(c)
val count = num + acc
val ret = if (count > 10) num.also { sb.append('/') } else count
ret.also { sb.append(c) } // `ret` returned to ^fold, next time will be passed as acc
}
println(sb.toString())
}
If you want a result in List<Char> type:
val data = "12493419133"
val result = mutableListOf<Char>()
var sum = 0
data.asSequence().forEach {
val v = Character.getNumericValue(it)
sum += v
if (sum > 10) {
result.add('/')
sum = v
}
result.add(it)
}
println(result.joinToString(""))

A very basic exercise help-----Kotlin

Im trying to do this exercise
https://www.hackerrank.com/challenges/compare-the-triplets/problem?h_r=next-challenge&h_v=zen
I already wrote the code but the result is not right and for my eyes its all good
Could somebody pls tell me whats wrong??
thx
import java.util.Scanner
fun main(){
var loop = 0
var score = Array<Int>(2){0}
val reader = Scanner(System.`in`)
var alice:String = readLine().toString()
var bob:String = readLine().toString()
val numerosa: List<String> = alice.split(" ")
val numerosb:List<String> = bob.split(" ")
for(a in 3..3) {
when (numerosa[loop].toInt()) {
in numerosb[loop].toInt() + 1..100 -> score[0] += 1
in numerosb[loop].toInt() - 1..0 -> score[1] += 1
}
loop += 1
}
println("${score[0]} ${score[1]}")
}
You could do it something like this, you have multiple variables which were not required so I cleaned up the code.
val score = Array(2) { 0 }
val aliceNumbers = readLine()!!.split(" ").map(String::toInt)
val bobNumbers = readLine()!!.split(" ").map(String::toInt)
require(aliceNumbers.size == 3 && bobNumbers.size == 3) { "There must be 3 numbers for each" }
require(!aliceNumbers.any { it !in 1..100 } || !bobNumbers.any { it !in 1..100 }) { "Numbers must be in range 1 to 100" }
for (a in 0..2) {
if(aliceNumbers[a] > bobNumbers[a]) score[0] += 1
if(aliceNumbers[a] < bobNumbers[a]) score[1] += 1
}
println("${score[0]} ${score[1]}")