Getting java.lang.NumberFormatException when trying to convert string to ascii

70 Views Asked by At

I am trying to convert a string to its ascii equivalent using ".toInt", and I am repeatedly getting this error:

java.lang.NumberFormatException: For input string: "'_'"
  java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
  java.lang.Integer.parseInt(Integer.java:654)

This is the line it is failing at:

P.map[Expression]{ case y => Chrc(y.toInt)}

Chrc is a parser that returns a string.

I have tried just doing

val x = '_'
println(x.toInt) 

outside the block of code I am writing in and it works, so the issue is to do with this sentence and the fact that i am trying to change it to an integer inside the Chrc class. Is there another way to write this?

1

There are 1 best solutions below

0
Seth Tisue On

The problem is reproducible as follows:

scala> val x = "'_'"
val x: String = '_'
                                                                                                    
scala> x.toInt
java.lang.NumberFormatException: For input string: "'_'"
  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:786)
  at scala.collection.StringOps$.toInt$extension(StringOps.scala:908)
  ... 32 elided

Here, x is a String. That's different from the code you supplied:

scala> val x = '_'
val x: Char = _
                                                                                                    
scala> x.toInt
val res1: Int = 95

in which x is a Char.

It is a peculiarity of both Scala and Java that the Char type (in Java, char with a small c) is an integer type, and thus toInt is a numeric conversion giving you the ASCII value of the character, rather than parsing it.