1

I am trying to print the range of numbers into a text file using Scala.

Here is my code:

package test

import java.io._

class Normal {
    def function(N:Double,File:String) {
        val rangetest = ((-N / 2) to (N / 2))
        val pw = new PrintWriter(new File(File))
        pw.write(rangetest)
        pw.close
    }
}

object normal_distribution extends App {
    val N = 50000.toDouble
    val file = "/home/Desktop/output_normal.txt"
    val normal_obj = new Normal
    normal_obj.function(N, file)
}

But I am getting an error with line

pw.write(rangetest)

Error message: overloaded method value write with alternatives: (x$1: String)Unit <and> (x$1: Array[Char])Unit

<and> (x$1: Int)Unit cannot be applied to

(Range.Partial[Double,scala.collection.immutable.NumericRange[Double]])

I am not able to print the range of values.

Pavel
  • 1,519
  • 21
  • 29
user2507238
  • 51
  • 3
  • 8
  • You need to convert rangetest val, which is a type of Range, to a string first. If I'm not mistaken you can use `rangetest.mkString(",")` – sercanturkmen Oct 14 '17 at 08:34
  • 1
    Possible duplicate of [How to write to a file in Scala?](https://stackoverflow.com/questions/4604237/how-to-write-to-a-file-in-scala) – sercanturkmen Oct 14 '17 at 08:50

2 Answers2

0

You need to convert you rangetest to a list first by specifying step because you are in RichDouble domain etc

Here is a code:

def function(N:Double,File:String) {

val rangetest  = (-N/2) to (N/2)

val step = 0.01

val sep = " "

val rangeByStep = rangetest.by(step)

val list = rangeByStep.toList

val str : String = list.mkString(sep)

val pw = new PrintWriter(new File(File))

pw.write( str )

pw.close

}

Pavel
  • 1,519
  • 21
  • 29
0

The concise one line:

new PrintWriter("range.txt") { write( 0.0 to 1.0 by 0.25 mkString(" ")); close }