3

When I run the following program :

object Problem {
  def main(args: Array[String]) = {
    val v = 53.toString
    val w = v(0).toInt
    println(w)
  }
}

it prints out 53, instead of what I would have expected, 5. Can someone help me understand why?

UPDATE: The same thing happens if I use charAt instead of the array syntax

2 Answers 2

9

53 is the ASCII value for the character '5'. Try 63.toString and you'll see 54 after v(0).toInt.

Use .asDigit to convert a Char to its Int value. In other words, '5'.toInt == 53 but '5'.asDigit == 5.

Sign up to request clarification or add additional context in comments.

Comments

0

Your code prints 53 because 53 is the ASCII value for the character '5'.

You will need to make the following changes if you want to see 5 as an answer. Hope it helps to clarify.

//Using charAt() should work, and print `5` as expected.

object Problem {
  def main(args: Array[String]) = {
    val v = 53.toString
    val w = v.charAt(0)
    println(w)
  }
}


Similarly, removing the `toInt()` should also print '5'.

object Problem {
  def main(args: Array[String]) = {
    val v = 53.toString
    val w = v(0)
    print(w)
  }
}

7 Comments

The first example is not 5 because the ASCII value of 5 is 53. It is 5 because 5 is the first character in the string "53". ASCII values are irrelevant here.
you are right, edited now. Thanks michael-mior@.
The answer still states that the code prints 53 because 53 is the ASCII value for '5'.
right michael-mior@, but I was referring to the code from the question... I think now should clearer right?
The explanation is still incorrect though. The code printing 53 has nothing to do with ASCII values.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.