So far we have seen the most basic programs. Now we are going to level up this a little bit. How to read and print the value of the Data Types in scala programming? In this program, we are going to take the user input and then print it to the console screen.
Scala Program to read and print the value of the String
object divineseo{
def main(args:Array[String]){
var str:String=""
Console.println("Enter your string: ")
str = scala.io.StdIn.readLine()
println("Entered string is: "+str)
}
}
The that you need to understand is that we use Console.println("Enter your string: ") to print the statement in console screen. But, it is not the only way to do that. You can also use print("Enter Your String: ")
to print the statement in the console screen as we do in Python.
str = scala.io.StdIn.readLine()
If you want to take the string input from the user then use the readLine() command.
Output
Enter your string:
Entered string is: divineseo
You have to enter your string in Stdin Inputs before the compilation of the program.
Scala Program to read and print the value of the Integer Variable
object divineseo{
def main(args:Array[String]){
var int:Integer=0
Console.println("Enter your integer: ")
int = scala.io.StdIn.readInt()
println("Entered Integer is: "+int)
}
}
Note: Use the scala.io.StdIn.readInt()
command if you want to take input as an integer variable.
Output
Enter your integer:
Entered Integer is: 10
Scala Program to read and print the value of the Float Variable
object divineseo{
def main(args: Array[String]){
var number: Float=0
Console.println("Enter the Float Value")
number=scala.io.StdIn.readFloat()
println("Entered Float Value is: "+number)
}
}
Note: Use the scala.io.StdIn.readFloat()
command if you want to take input as a Float variable.
Output
Enter the Float Value
Entered Float Value is: 29.89
Scala Program to read and print the value of the Character Variable
object divineseo{
def main(args: Array[String]){
var character: Char=0
Console.println("Enter the Character")
character=scala.io.StdIn.readChar()
println("Entered Character is: "+character)
}
}
Note: Use the scala.io.StdIn.readChar()
command if you want to take input as a Character Variable.
Output
Enter the Character
Entered Character is: o