0% found this document useful (0 votes)
2 views

Operators UserInput Week20part2 Block A

The document covers the basics of programming in Scala, focusing on variables, data types, operators, and user input. It explains how to declare variables, use arithmetic and relational operators, and read input from the keyboard. Additionally, it highlights the importance of type inference and dynamic program execution through command line arguments.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Operators UserInput Week20part2 Block A

The document covers the basics of programming in Scala, focusing on variables, data types, operators, and user input. It explains how to declare variables, use arithmetic and relational operators, and read input from the keyboard. Additionally, it highlights the importance of type inference and dynamic program execution through command line arguments.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 20

CTEC1703

Computer Programming

Operators and User Input


Week 20 part 2

Introduction to programming in Scala (Block A: week 20)

1
Objectives
 Further explore variables and data types

 Understand the different kinds of operators


available and their purpose

 Write programs that receive user input from


the keyboard

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

 Widening conversions mean it is possible to assign an


Int to a Long, or Float to a Double but not vice
versa. A Long can hold the entire range of integer
values, but an Int cannot hold all long values.

 Of course if we assign an integer to a string or vice


versa we get a type mismatch error in both cases.

3
Code blocks and block scope
 A block is a sequence of expressions evaluated
successively that are enclosed in braces { }.

 When declaring a variable you need to be aware of the


block it is within as this will determine the visibility of
the variable within the program.

 A variable cannot be accessed from within a block that


is outside of the one within which it was declared – it is
said to be out of scope.

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"

 If the values or types are different they must either go


on a separate line or be separated by a semi-colon.
 var pi: Double = 3.14159
 var flag: Boolean = true
 var first: Char = 'a'; var last: Char = 'z'

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.

 Reassignment is acceptable for vars but not for vals:


 var x: Int = 5; val y: Int = 10;
 x = x * x //OK – 25
 x = 1 + y //OK – 11
 y = 5 //error – reassignment to val
 y = y + 1 //error – reassignment to val

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

 Although beyond this discussion, pattern matching and


tuples can be combined with type inference for elegant
multiple assignments:
 val (a, b, c) = (22, 0.5, "fred")
//a is an Int, b a Double and c a String
7
Arithmetic Operators
 + (add) – (subtract) * (multiply) / (divide) and %
(modulus, i.e. remainder)

 * / % have precedence over + and -, otherwise


calculation carried out left to right.
 e.g. 3 + 4 * 2 will evaluate 4 * 2 then add 3 to the result of that.

 We can use parentheses ( ) to reinforce this or to


ensure certain expressions are evaluated first.
 e.g. (3 + 4) * 2 will evaluate 3 + 4 then multiply the result by 2.

8
Arithmetic Operators example
 We use the arithmetic operators with numeric types.

object ArithmeticDemo {
def main(args: Array[String]): Unit = {

var num, x, y: Int = 5


num = 5 + y
num = num / y
num = y + x
num = num % x
println("What is num? " + num);
}
}

9
Integer division
 Integer variables can only hold whole numbers.

 When you carry out division where both operands are


integers it will truncate the result – this simply means
removing anything after the decimal point.

 For example a result of 2.9 would truncate to 2.


Dividing 5 by 2, would result in 2, not 2.5. However
each of the following would result in 2.5:
 5.0 / 2 5 / 2.0 5.0 / 2.0

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.

 We can also treat characters as numbers based on


their ascii value, e.g. 'a' + 1 gives us 98, i.e. 'b' in ascii.

println("hello" + " world") //hello world


println("Number is " + 5 + 5) //Number is 55
println("Number is " + (5 + 5)) //Number is 10
println("foo" * 3) //foofoofoo
println(('a' – 32).toChar) //A
11
Further Assignment Operators
 += (add and assign) –= (subtract and assign)
*= (multiply and assign) /= (divide and assign) and
%= (modulus and assign)

 These shortcut reassignment operators can only be


used with vars, not vals.

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:
== != > >= < <=

 These compare one operand to another , where the


operand may be a variable identifier or literal value,
and produce a Boolean result of true or false, e.g.
mark >= 40 x == y
z != 0

13
Logical Operators
 There are three logical operators that can also be
used as part of Boolean expressions:
&& (AND) || (OR) ! (NOT)

 Logical AND and OR compare two Boolean


expressions, whilst logical NOT inverses a Boolean
expression, e.g.
mark >= 40 && mark <= 100
x == y || x == z
!(x >= 40 && x <= 100)
14
Read input from the keyboard
 To make the execution of your programs dynamic you
can read input from the keyboard using the standard
input stream assigned to the Run tool window (IntelliJ).

 The read methods in the default scala package are


deprecated and have been redefined in the package
scala.io.

 The StdIn object in this package comes with a variety


of methods for reading numbers, characters and
strings, e.g. readInt, readChar, readLine.

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._

 We can get a runtime exception such as a


NumberFormatException if our input cannot be
converted to the target data type, e.g. Int.

 You should prompt the user (e.g. by using println) to


tell them the data you expect them to input. When
reading strings you can use a shorthand
readLine(String) method where the string you
pass is the prompt.
16
Reading input example
println("Input your age")
var age: Int = readInt()

println("Input your initial")


var initial: Char = readChar()

println("Input your surname")


var name: String = readLine()

var addr: String = readLine("Input an address\n")

//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).

 The arguments are captured inside an Array of strings,


which is part of the main method definition.

def main(args: Array[String]): Unit = {


var first: String = args(0)
var second: Int = args(1).toInt
var len: Int = args.length
18
Summary
 Variables can be declared in different ways and take
advantage of type inference.

 Standard arithmetic can be achieved using the


predefined arithmetic and assignment operators.

 Relational and logical operators can combine to forma


variety of Boolean expressions.

 User input allows us to produce more dynamic


programs.

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

You might also like