Comparison in Kotlin using Boolean - kotlin

I'm super new to programming and everything, and currently I'm joining this course by Google. So there is one exercise that I have to compare the time I've spent on using my phone yesterday and today. Below is the code that I've written. I need the output to be true , false, false but my output was true, false, true . I've tried to solve but it just turned worse. I need help!
fun main() {
var timeSpentToday = 300
var timeSpentYesterday = 250
println(timeSpent(timeSpentToday, timeSpentYesterday))
println()
println(timeSpent(300, 300))
println()
println(timeSpent(200, 220))
println()
}
fun timeSpent(today: Int, yesterday: Int): Boolean {
val today = 300
val yeseterday = 250
return today > yesterday
}
I tried to change the input value and it works if I change the penultimate println to println(timeSpent(200,300) . However, it doesn't work if the number is in range of 200 to 290

fun timeSpent(today: Int, yesterday: Int): Boolean {
val today = 300
val yeseterday = 250
return today > yesterday
}
Well, you fully ignore the value of today that is passed into timeSpent, replacing it with a new variable that always has the value 300. You also try to do that with yesterday, but a typo actually means you do the right thing. In any event, timeSpent should have two of its three lines deleted:
fun timeSpent(today: Int, yesterday: Int): Boolean {
return today > yesterday
}

Related

It should return true but it says false and I dont know why

I am programming something and I was testing something with assertEquals and I am pretty sure that it should return true but the test says it is false. The value im testing is "hasEnded"
I will show you the relevant code to my case:
Note: Everything I deleted was tested already and kept the only important code to my case "hopefully"
class Schwimmen(
var hasEnded: Boolean = false
)
fun nextTurn() {
val game = rootService.currentGame
game.hasEnded= checkForEnd()
private fun checkForEnd(): Boolean {
val game = rootService.currentGame
return (game.cards.size < 3 && game.playerPassCounter >= game.players.size) ||
(game.activePlayer == game.endGamePlayer)
}
fun testNextTurn(){
testRootService.schwimmenService.startSchwimmen(players)
testRootService.currentGame?.cards?.clear()
testRootService.currentGame?.playerPassCounter = 5
assertEquals(true, testRootService.currentGame?.hasEnded)
}
The Test failed and I got: AssertionFailedError: expected: "true" but was: "false"
I found the answer:
I forgot to call "nextTurn()" to run checkForEnd() in test
#Test
fun testNextTurn(){
testRootService.schwimmenService.startSchwimmen(players)
testRootService.currentGame?.cards?.clear()
testRootService.currentGame?.playerPassCounter = 5
**testRootService.schwimmenService.nextTurn()**
assertEquals(true, testRootService.currentGame?.hasEnded)
}

Why am I geting a blank when I run this string funtion in Kotlin?

So I was solving a problem that required me to put unique characters in a string without using a data structure.
fun main(){
val s1 = "fhfnfnfjuw"
val s2 = "Osayuki"
val s3 = "Raymond"
val s4 = "Aseosa"
uniqueChar(s1)
}
fun uniqueChar(s: String){
val updatedString = ""
s.forEach {c ->
if (!updatedString.contains(c)){
updatedString.plus(c)
}
}
println(updatedString)
}
And getting this error
I'm not sure what's going on and why I'm getting a blank. I'm sure it's an easy fix, but I can't see it. Any help is appreciated.
updatedString.plus(c) does not change updatedString. It creates a new string, including the character c. Since you don't do anything with that, the new string goes...nowhere.
Instead, you probably wanted updatedString = updatedString.plus(c) -- or something better with StringBuilder, but that's the closest version to your code.

How do I pull entries from an ArrayList at random in Kotlin?

This is my first Kotlin project. I am learning as I go and I have reached a roadblock.
I have an ArrayList of questions that I want to pull into that app in a random order. I've tried assigning the .random to the point where the question is assigned (right now it is set to CurrentPosition-1) but that only randomized the question and didn't pull the correct answers along with the questions.
How do I either bundle the answers to the question or is there a better way to get the questions to shuffle in order? I plan on having 50+ questions but only 10 will show each time the test is taken. I don't want the same 10 questions showing each time the user opens the test.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_quiz_questions)
mQuestionsList=Constants.getQuestions()
setQuestion()
}
private fun setQuestion(){
val question = mQuestionsList!![mCurrentPosition-1]
defaultOptionsView()
if(mCurrentPosition == mQuestionsList!!.size){
submitBtn.text = "Finish"
}else{
submitBtn.text = "Submit"
}
progressBar.progress = mCurrentPosition
tv_progress.text = "$mCurrentPosition" + "/" + progressBar.max
tv_question.text = question!!.question
test_image.setImageResource(question.image)
tvOptionOne.text = question.optionOne
tvOptionTwo.text = question.optionTwo
tvOptionThree.text = question.optionThree
tvOptionFour.text = question.optionFour
}
private fun defaultOptionsView(){
val options = ArrayList<TextView>()
options.add(0, tvOptionOne)
options.add(1, tvOptionTwo)
options.add(2, tvOptionThree)
options.add(3, tvOptionFour)
Here is my Array
object Constants{
const val TOTAL_QUESTIONS: String = "total_questions"
const val CORRECT_ANSWERS: String = "correct_answers"
fun getQuestions(): ArrayList<Question>{
val questionsList = ArrayList<Question>()
val q1 = Question(
R.drawable.questionmark,
1,
"Who is Regional Manager of\n Dunder Mifflin Scranton?",
"Michael",
"Jim",
"Pam",
"Dwight",
1,
)
I appreciate any help at all. Thank you in advance.
list.shuffled().take(10) And make your mQuestionsList property type List instead of ArrayList since you don’t need to modify it after retrieval. You should also probably make it lateinit or initialize it at its declaration site so you won’t have to make the type nullable and have to resort to !!, which is generally a code smell. So I would declare it as var mQuestionsList: List<Question> = emptyList() and whenever you want new values do mQuestionsList = Constants.getQuestions().shuffled().take(10).

Currency will not show second decimal in Kotlin [duplicate]

I am facing an issue where I need to do some calculations with a number like for example 5000,00 multiplied it by (1,025^3).
So in this case 5000,00 * (1,025^3) = 5385,45
So my question is, how can I format the number 5385,45 to be like 5.385,45 using decimal format maybe?
I tried by myself and I did this piece of code that outputs 5385,45 in the app but not 5.385,45
var interestValue = (5000,00*(Math.pow(1.025,yearValue)))
val number = java.lang.Double.valueOf(interestValue)
val dec = DecimalFormat("#,00")
val credits = dec.format(number)
vValueInterest.text = credits
This is the format you need:
val dec = DecimalFormat("#,###.##")
will print:
5.384,45
if you need always exactly 2 digits after the decimal point:
val dec = DecimalFormat("#,###.00")
val num = 1.34567
val df = DecimalFormat("#.##")
df.roundingMode = RoundingMode.CEILING
println(df.format(num))
When you run the program, the output will be:
1.34
Check:
https://www.programiz.com/kotlin-programming/examples/round-number-decimal
The "most Kotlin-esque" way I found to do this sort of formatting is:
"%,.2f".format(Locale.GERMAN, 1234.5678) // => "1.234,57"
"%,.2f".format(Locale.ENGLISH, 1234.5678) // => "1,234.57"
"%,.2f".format(1234.5678) // => "1,234.57" for me, in en_AU
Note though that even though this is Kotlin's own extension method on String, it still only works on the JVM.
For those looking for a multiplatform implementation (as I was), mp_stools is one option.
Used:
%.numberf
fun main(args: Array<String>) {
var A: Double
A = readLine()!!.toDouble()
var bla = A*A
var calculator = 3.14159 * bla
println("A=%.4f".format(calculator))
}
Try val dec = DecimalFormat("#.###,00"). For examples of DecimalFormat check this link.

Removing unncecessary parts from String

I'm consuming a client that I cannot change and it sends me data that looks like that:
"BOOKING - PAID (price.amount=70, price.currency=EUR)"
and I would like to retrieve from that only 70 EUR
What is the best way to do such thing in kotlin? I didn't find any removeAll("", "", ...) functions for String, only replace but would have to chain them to remove both price.amount and price.currency.
EDIT:
Need to get BOOKING - PAID (70 EUR) actually, forgot about that part.
Thinking about it and as you updated your question to really remove only a part from the string, here are some approaches for removing several strings from a given string:
Using regex:
input.replace("""(price\.(amount|currency)=|,)""".toRegex(), "")
Using a list of strings to remove:
sequenceOf(input, "price.amount=", ",", "price.currency=")
.reduce { acc, rm -> acc.replace(rm, "") }
// alternatively using var:
var input = TODO()
sequenceOf("price.amount=", ",", "price.currency=")
.forEach { input = input.replace(it, "") }
Still: most of the time I would rather take the other route: extracting the information you require and just print that, as also Baptiste has shown in his answer. Otherwise you may start to expose answers of that service you didn't want to expose in the first place.
This sounds like a job for regular expressions!
fun main(args: Array<String>) {
val str = "BOOKING - PAID (price.amount=70, price.currency=EUR)"
// The expressions between parentheses will map to groups[1], groups[2] and groups[3] respectively
val reg = Regex("""(.*) \(price\.amount=([0-9]+), price\.currency=([A-Z]+)\)""")
// Apply the regular expression on the string
val results = reg.find(str)
results?.groupValues?.let { groups ->
// If results and groupValues aren't null, we've got our values!
val type = groups[1]
val price = groups[2]
val currency = groups[3]
println("$type ($price $currency)") // BOOKING - PAID (70 EUR)
}
// Or as suggested by #Roland:
results?.destructured?.let { (type, price, currency) ->
println("$type ($price $currency)") // BOOKING - PAID (70 EUR)
}
}
Regular expressions allow you to take a string as entry, and find a pattern in it. They're quite used in all languages, you can find more info about them all over the place.
EDIT: edited for the updated question. I chose to treat "BOOKING - PAID" as a single string, but there's an infinite number of ways to do it, depending on your granularity needs; and honestly, at that point a regex might be a bit overkill. :)
Without regex by string manipulation and assuming that this is the pattern:
fun main(args: Array <String> ) {
val str = "BOOKING - PAID (price.amount=70, price.currency=EUR)"
val type = str.substringBefore("(").trim()
val price = str.substringBeforeLast(",").substringAfter("=")
val currency = str.substringAfterLast("=").substringBefore(")")
val result = "$type ($price $currency)"
println(result)
}
will print
BOOKING - PAID (70 EUR)
Edit: I use str.substringBeforeLast(",") to get the price, in case , could be used as a delimeter for decimal part in the number