BlackZero BlackZero - 7 months ago 30
Scala Question

How to add print(.....),println(..) to String scala

def printTruthtable(n : Int):String = {
var rows = Math.pow(2,n).toInt;
var i = 0;
var str : String = "";
for(i<-0 until rows)
var j = n-1 ;
for(j<-(0 to n-1).reverse)
return postfix.toString;}

When i run println(postfix) i just see a lot of () help me to add print((i/(Math.pow(2,j).toInt))%2) into a string.Thanks


print and println doesn't return a String, it prints to the standard output. The () you are seeing in the console is scala Unit - which is a tuple of 0 elements, since print and println return Unit (which is similar in terms of semantics to javas void). To append the evaluated String value of your calculation simply do this

str += ((1 / (Math.pow(2, 1).toInt)) % 2).toString

Then use print or println to output it to the standard out:


However, to make your code more idiomatic, I would look at

Looking at those a bit more concise solution:

def truthtable(n: Int) = (0 until Math.pow(2, n).toInt).map { i =>
  (0 to n - 1) => (i / (Math.pow(2, j).toInt)) % 2).mkString("")

This returns the truthtable as a String then all you have to do is print it:


Note that I didn't check if your algorithm is correct, just refactored what you already have.