NumberFormatException in Kotlin (IntelliJ) - kotlin

Here is what I am trying to do, I want the user to enter whatever number and it should be displayed, but I am getting this error.
import java.util.*
This is my code
fun main(){
print("Enter your age")
var age = readLine()!!.toInt()
print(age)
}
And the error I am getting is
Enter your age 40
Exception in thread "main" java.lang.NumberFormatException: For input string: " 40"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:654)
at java.base/java.lang.Integer.parseInt(Integer.java:784)
at HelloKt.main(Hello.kt:5)
at HelloKt.main(Hello.kt)
Process finished with exit code 1

You are writing a space in front of the 40 as indicated by the error " 40".
A solution could be is to trim all leading and trailing whitespaces from the readLine, like this:
var age = readLine()!!.trim().toInt()

Related

Read one or two variables alternately in one line

I have declared 2 variables to read from console but on other case i want to read just one of them but i can't.
My code:
print("Enter two numbers in format: {source base} {target base} (To quit type /exit) ")
val (sourceBase, targetBase) = readLine()!!.split(" ")
`I can't type /exit because i've got IndexOutOfBoundsException.
Any tips?
Edit: Thank you all for respond, especially lukas.j, it's working now.
Add a second element, an empty string, if the splitted readLine() contains less than 2 elements:
val (sourceBase, targetBase) = readLine()!!.split(" ").let { if (it.size < 2) it + "" else it }

how to read mutliple lines of string into one variable using readln() in kotlin?

example:
a variable
val str = readln().replace("[^A-Za-z0-9 ] \\s+".toRegex(),"").trim()
should read multiple lines of input value, input value will be like this
heading
----------
topic1
topic2
or like this
heading
-------
a) topic1
b) topic2
input may contain special characters or tabs or spaces we need to remove them also
I don't know what your Regex is trying to do, but that's not really your question.
How do you know when the user has finished their input - a special word or an empty line?
Assuming an empty line, here's how you can get all the content
println("Enter something:")
var lines = ""
do {
val line = readLine()
lines += "${clean(line)}\n"
} while (!line.isNullOrBlank())
println("User input:\n$lines")
private fun clean(line: String?): String? {
return line?.replace("[^A-Za-z0-9 ] \\s+".toRegex(),"")?.trim()
}

Parse a line of input into different types in Kotlin

this problem need print data types
https://codeforces.com/group/MWSDmqGsZm/contest/219158/problem/B
but he need inputs on just one line with space between each data type
this is my code , what's the problem
import java.util.Scanner
fun main(args:Array){
val scanner = Scanner(System.`in`)
var a:Int=readLine()!!.toInt()
var b:Long=readLine()!!.toLong()
var c:Char=scanner.next().single()
var d:Float=readLine()!!.toFloat()
var e:Double=readLine()!!.toDouble()
println(a)
println(b)
println(c)
println(d)
println(e)
}
Exception in thread "main" java.lang.NumberFormatException: For input string: "45 65896532145 a 45.23 65423.325"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:660)
at java.base/java.lang.Integer.parseInt(Integer.java:778)
at Test_1Kt.main(test 1.kt:7)
The problem is that you cannot parse the entire input as integer, as the input you expect is set of values with space between. Space itself cannot be parsed into Integer (this is what cause the exception)
To solve this, first, you need to split the input and parse each of the element. You can split it using kotlin built in function, i.e.
val input = readLine() ?: ""
val inputElement = input.split(" ")
Here, the inputElement is a string array that consist all of element from your input. Next, you need to parse each of the element by the inputElement index
val a:Int=inputElement[0].toInt()
val b:Long=inputElement[1].toLong()
val c:Char=inputElement[2].single()
val d:Float=inputElement[3].toFloat()
val e:Double=inputElement[4].toDouble()
println(a)
println(b)
println(c)
println(d)
println(e)

Scala Doobie PSQLException: ERROR: syntax error at end of input when use "Like %"

I am using PostgreSQL 12.1 with Scala and Doobie. Getting exception when trying to do query with LIKE % syntax. It works without %.
My code:
implicit val cs = IO.contextShift(ExecutionContexts.synchronous)
val driver = "org.postgresql.Driver"
val connectionString = "jdbc:postgresql:postgres"
val user = "postgres"
val pass = "P#ssw0rd"
lazy val xa = Transactor.fromDriverManager[IO](driver, connectionString, user, pass)
def findNamePref(title: String): Option[Book] = {
val s = sql"SELECT * FROM books WHERE title LIKE $title%".query[Book].option
s.transact(xa).unsafeRunSync()
}
Exception:
Exception in thread "main" org.postgresql.util.PSQLException: ERROR:
syntax error at end of input Position: 41 at
org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2505)
at
org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2241)
at
org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:310)
at
org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:447)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:368) at
org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:158)
at
org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:108)
at
doobie.free.KleisliInterpreter$PreparedStatementInterpreter.$anonfun$executeQuery$2(kleisliinterpreter.scala:956)
at
doobie.free.KleisliInterpreter.$anonfun$primitive$2(kleisliinterpreter.scala:112)
at
cats.effect.internals.IORunLoop$.cats$effect$internals$IORunLoop$$loop(IORunLoop.scala:87)
at
cats.effect.internals.IORunLoop$.startCancelable(IORunLoop.scala:41)
at
cats.effect.internals.IOBracket$BracketStart.run(IOBracket.scala:86)
at
cats.effect.internals.Trampoline.cats$effect$internals$Trampoline$$immediateLoop(Trampoline.scala:70)
at cats.effect.internals.Trampoline.startLoop(Trampoline.scala:36)
at
cats.effect.internals.TrampolineEC$JVMTrampoline.super$startLoop(TrampolineEC.scala:93)
at
cats.effect.internals.TrampolineEC$JVMTrampoline.$anonfun$startLoop$1(TrampolineEC.scala:93)
at
scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.scala:18)
at
scala.concurrent.BlockContext$.withBlockContext(BlockContext.scala:94)
at
cats.effect.internals.TrampolineEC$JVMTrampoline.startLoop(TrampolineEC.scala:93)
at cats.effect.internals.Trampoline.execute(Trampoline.scala:43) at
cats.effect.internals.TrampolineEC.execute(TrampolineEC.scala:44) at
cats.effect.internals.IOBracket$BracketStart.apply(IOBracket.scala:72)
at
cats.effect.internals.IOBracket$BracketStart.apply(IOBracket.scala:52)
at
cats.effect.internals.IORunLoop$.cats$effect$internals$IORunLoop$$loop(IORunLoop.scala:136)
at
cats.effect.internals.IORunLoop$RestartCallback.signal(IORunLoop.scala:355)
at
cats.effect.internals.IORunLoop$RestartCallback.apply(IORunLoop.scala:376)
at
cats.effect.internals.IORunLoop$RestartCallback.apply(IORunLoop.scala:316)
at cats.effect.internals.IOShift$Tick.run(IOShift.scala:36) at
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
Dependencies:
scalaVersion := "2.13.1"
lazy val doobieVersion = "0.8.8"
libraryDependencies ++= Seq(
"org.tpolecat" %% "doobie-core" % doobieVersion,
"org.tpolecat" %% "doobie-postgres" % doobieVersion,
"org.tpolecat" %% "doobie-specs2" % doobieVersion
)
The code will replace the content of $title with the value from the function parameter.
The query however contains a % after the parameter. Once replaced with a value, the SQL would look like ... WHERE title LIKE 'myTitle'%, which is invalid.
You can concatenate the % to the given parameter
val s = sql"SELECT * FROM books WHERE title LIKE $title || '%'".query[Book].option
which would translate to ... WHERE title LIKE 'myTitle' || '%' then to ... WHERE title LIKE 'myTitle%'
The why described already JGH.
A simple fix would be to add % to the parameter.
Request:
val s = sql"SELECT * FROM books WHERE title LIKE $title".query[Book].option
Examples:
findNamePref("Title")
findNamePref("Tit%")
findNamePref("%itle")
findNamePref("%")
The reason you got this error is you inscribed a string variable in a string itself i.e. title in your case. On usage, the string variables gets substituted to its value hence inscribing a string value within double quotes is again a syntax error. So,
you should use title explicitely by concatenation of the title value to the select query string.
"select * from.... Where title like %"
+title+"%" ;
Thanks to all. This is what i use after all:
sql"SELECT * FROM books WHERE title LIKE ${title+"%"}".query[Book].option

iterate list of data classes not working as expected

I have a list of data classes that I am trying to iterate over.
Here is the data class and where it is created.
data class BgaResponse(val columnName: String, val restricted: Boolean, val predictionValue: Double)
val bgaResponse: List<BgaResponse>? = callBgaEndpoint(bgaRequest)
printing bgaResponseshows this:
[{columnName=col1, restricted=false, predictionValue=0.9963}, {columnName=not_here, restricted=false, predictionValue=0.995941}]
I first tried using forEach:
bgaResponse?.forEach {
println(it)
}
this prints nothing. Next i tried accessing each element by index:
for(i in 0 until bgaResponse!!.size) {
println(bgaResponse[i])
}
this prints each element as expected:
{columnName=col1, restricted=false, predictionValue=0.9963}
{columnName=not_here, restricted=false, predictionValue=0.995941}
I tried printing bgaResponse[i].columnName but nothing prints again. Now this isnt making any sense.
Lastly I try:
for(i in 0 until bgaResponse!!.size) {
val x: BgaResponse= bgaResponse[i]
}
this should work, my IDE is telling me bgaResponse[i] is a BgaResponse. This throws back an error:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.package.something.placeholder.model.BgaResponse