Warlock
Warlock

Reputation: 186

Read integer from a line in scala

scala

I'm new to scala programming.i'm writing a code to read the integers from a line .what i did is :

  1. read the line of interger(1 2 4 5 6)
  2. read the character at 0,2,4,6 postion since space 1,3,5 are blank space, but when it comes to read 10 only 1 is reed .

my code is

 val size: Int = Console.readInt // First line read the no of integers
    val reading: String = Console.readLine // String of integer(1 4 6 7 8)

    val readingSize: Int = reading.length

    var inp: Array[Int] = new Array[Int](size)
    for (a <- 0 until readingSize if (a % 2 == 0)) inp(a / 2) = reading(a) //converting into integer array(will be ASCII value)
      println("Output : " )
       for (b <- 0 until inp.length) 
         print(inp(b).toChar + " " )

So for example for input (1 3 5 6 7) it works but for (1 2 10 9) it will stop at 1 2 1.

i'ma beginner and so i don't whether this is completely bad logic for reading scala. Hope my question is clear Thanks in advance (and also input should in single with a single space between value)

Upvotes: 1

Views: 3279

Answers (2)

Mamuka
Mamuka

Reputation: 102

I know what is your problem. if for statement you have "if (a % 2 == 0)" where a is the index of string 'reading'. This code will work only for digits, because if I have string (3 5 4 8 7) in this string index of spaces is odd, and if I take only even indexed numbers I will get the resulting numbers. But if I had string (23 4 17 4 2) here is 3 is standing on odd index, and because of constraint"(a % 2 == 0)" I will simply lose it. In your case for (1 3 5 6 7) it will work just fine, because you have only digits there, but for (1 2 10 9), it will print 1, then miss 0, and print space and that's it. It will actually print 1,2,1 and space, but you cant see space, that's why you thought it stopped at 1.

But there is a simpler way of doing this, you can take some string st, which is numbers and spaces, and take st.split(" ").toList which will give you a list of desired ints only in string typed, and for this list you can use map function like this: list map (p => Integer.parseInt(p)) what it does is it will take each element p from the list and replace it with the resulting element which we get by Integer.parseInt(p) function.

Upvotes: 0

om-nom-nom
om-nom-nom

Reputation: 62835

If all your integers from std in are delimited with spaces, why don't you just split them basing on known separator?

"1 2 10 9".split(' ')
// Array(1, 2, 10, 9)

Upvotes: 2

Related Questions