Operators UserInput Week20part2 Block A
Operators UserInput Week20part2 Block A
Computer Programming
1
Objectives
Further explore variables and data types
2
Data type ranges and assignment
Numeric types (including Char) have a range of values
(between a min and max) that can be assigned to them
3
Code blocks and block scope
A block is a sequence of expressions evaluated
successively that are enclosed in braces { }.
4
Multiple variable declaration
You may declare multiple variables in the same
statement if they are of the same type and value.
var x, y, z: Int = 55 //assigns 55 to each
var a, b: String = "hi" //both assigned "hi"
5
The val keyword
A declaration starts with either var or val:
var – the data is truly 'variable' and can be changed.
val – a constant variable, or more simply a value.
6
Type inference
The data type of a variable can be inferred by the
compiler from the value or expression you assign to it.
var x = 20 //x is inferred as an Int
var y = 8 * 5 + 2 //y is an Int
var name = "fred" //name is a String
8
Arithmetic Operators example
We use the arithmetic operators with numeric types.
object ArithmeticDemo {
def main(args: Array[String]): Unit = {
9
Integer division
Integer variables can only hold whole numbers.
10
Operators with strings and chars
As already seen + is used for string concatenation. We
can use * for concatenation n times. The latter must
follow a string however.
var x: Int = 5
x += 8 //expanded to x = x + 8 by the compiler
x *= 3 //expanded to x = x * 3 by the compiler
println("What is x? " + x)
12
Relational Operators
There are six relational operators that can be used as
part of Boolean expressions:
== != > >= < <=
13
Logical Operators
There are three logical operators that can also be
used as part of Boolean expressions:
&& (AND) || (OR) ! (NOT)
15
Read input from the keyboard (cont...)
We need to import the methods so that we can use
them, e.g. import scala.io.StdIn._
//yes, y, true, t (in upper or lower case) are true, anything else is false
println("Currently active?")
var active: Boolean = readBoolean()
17
Command line arguments
A program can be executed dynamically with different
command line arguments. We can input these via Run
> Edit Configurations, Program arguments (IntelliJ).
19
Suggested reading
Online Tutorials:
https://www.tutorialspoint.com/scala/
http://docs.scala-lang.org/
https://alvinalexander.com/scala/scala-programming-cookbook
-recipes-faqs
Textbooks:
Programming in Scala (3rd edition) by Martin Odersky
An Introduction to programming and problem-solving using
Scala (2nd edition) by Mark C. Lewis and Lisa L. Lacher
20