Skip to content

Instantly share code, notes, and snippets.

@linhmtran168
Created January 22, 2016 20:35
Show Gist options
  • Save linhmtran168/447706c7c075eb6e2b3c to your computer and use it in GitHub Desktop.
Save linhmtran168/447706c7c075eb6e2b3c to your computer and use it in GitHub Desktop.
FizzBuzz Scala
import java.io.IOException
import java.nio.file.{FileAlreadyExistsException, Files, Paths}
import scala.math.BigInt
/**
* Created by linhmtran on 1/23/16.
*/
object FizzBuzz extends App {
try {
val endNumber = BigInt(args(0))
val file = Paths.get(args(1))
Files.createFile(file)
val writer = Files.newBufferedWriter(file)
writer.write(System.currentTimeMillis().toString + "\n")
var i = BigInt(1)
var j = 1
while (i <= endNumber) {
writer.write(getOutput(j, i) + "\n")
if (j == 15) j = 1 else j += 1
i += 1
}
writer.write(System.currentTimeMillis().toString + "\n")
writer.close()
} catch {
case e: NumberFormatException => println("The end number is invalid")
case e: FileAlreadyExistsException => println("Please input a new file name")
case e: IOException => println("Error open writer")
}
def getOutput(index: Int, num: BigInt) = {
if (index == 15) "FizzBuzz"
else if (index % 3 == 0) "Fizz"
else if (index % 5 == 0) "Buzz"
else num.toString()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment