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

Remaining Scala Assignments

The document discusses Scala classes, objects, and assignments involving defining classes with constructors and methods, inheritance between classes, abstract classes and traits, and using lists and tuples in Scala programs. Several programming assignments provide examples of creating classes for bank accounts, players, shapes, and implementing traits.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views

Remaining Scala Assignments

The document discusses Scala classes, objects, and assignments involving defining classes with constructors and methods, inheritance between classes, abstract classes and traits, and using lists and tuples in Scala programs. Several programming assignments provide examples of creating classes for bank accounts, players, shapes, and implementing traits.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Assignment 14

/*Define a class Current Account (accNo, name, balance, minBalance).


Define appropriate constructors and operations withdraw(), deposit(),
viewBalance().
Create an object and perform operations
*/

import scala.io.StdIn._
import scala.util.control.Breaks._
class CurrentAccount(accno:Int,name:String,var balance:Float,minBalance:Float)
{

def this(accno:Int,name:String,balance:Float)
{
this(accno,name,balance,1000.0f)
}

def deposit(amt:Float)=balance+=amt

def withdraw(amt:Float)
{
if(balance - amt < minBalance)
println("Insufficient fund..")
else
balance = balance - amt
}
def getAccno():Int=return accno

def display() = println("Accno = "+accno+"\nName = "+name+"\nBalance =


"+balance)

def viewBalance() = println("Balance = "+balance)


}

object Ass14
{
def main(args : Array[String])
{
println("Enter no. of current accounts :")
var n = readInt
var arr =new Array[CurrentAccount](n)
var cnt=1
for(i<- 0 to n-1)
{
println("Enter name,opening balance : ")
var name=readLine
var bal=readFloat
arr(i)=new CurrentAccount(cnt,name,bal)
cnt=cnt+1
}
var ch:Int=0
do{
println("1.Deposit\n2.Withdraw.\n3.View balance\n4.Exit")
println("Enter your choice::")
ch=readInt
ch match{
case 1=>
println("Enter account no.")
var ac=readInt
var flag=false
breakable {
for(i<-0 to n-1)
{
if (ac==arr(i).getAccno)
{
println("Enter amount to deposit : ")
val amt=readFloat
arr(i).deposit(amt)
flag = true
break
}
}
}
if(flag==false)
println("Invalid account no.")

case 2=>
println("Enter account no.")
var ac=readInt
var flag=false
breakable {
for(i<-0 to n-1)
{
if (ac==arr(i).getAccno)
{
println("Enter amount to withdraw : ")
val amt=readFloat
arr(i).withdraw(amt)
flag = true
break
}
}
}
if(flag==false)
println("Invalid account no.")

case 3 =>
println("Enter account no.")
var ac=readInt
var flag=false
breakable {
for(i<-0 to n-1)
{
if (ac==arr(i).getAccno)
{
arr(i).viewBalance
flag = true
break
}
}
}
if(flag==false)
println("Invalid account no.")
case 4 =>
return
}
}while(ch!=4)

}
}

Assignment 16 :
Write a class Player (pno, pname, age). Define appropriate constructor & methods
for this class. Define two subclasses extending Player class- CricketPlayer
(noofinnings, battingavg, ballavg). FootBallPlayer (noofgames, noofgoals). Write
appropriate method and constructor for this classes. In main method accept the
details of no. of player & display the player details having batting average greater
than 50 and football player scoring more than 15 goals.
import scala.io.StdIn.{readInt,readLine,readFloat}
class Player
{
private var pno:Int=0
private var pname:String=null
private var age:Int=0
def this(pno:Int,pname:String,age:Int)
{
this()
this.pno=pno
this.pname=pname
this.age=age
}
override def toString()=s"Player No=$pno Name=$pname Age=$age"
def getPname():String=return pname
}
class
CricketPlayer(pno:Int,pname:String,age:Int,no_innings:Int,batavg:Float,ballavg:Flo
at) extends Player(pno,pname,age)
{
override def toString()=super.toString()+s"No of innings=$no_innings Batting
average=$batavg Balling average=$ballavg"
def getBatavg():Float=return batavg
}
class FootBallPlayer(pno:Int,pname:String,age:Int,no_matches:Int,goals:Int)
extends Player(pno,pname,age)
{
override def toString()=super.toString()+s"No of matches=$no_matches
Goals=$goals"
def getgoals():Int=return goals
}
object Ass16
{
def main(args: Array[String])
{
println("Enter no. of Players:")
var n:Int=readInt()
var arr=new Array[Player](n)
println("Enter Player Details :")
for(i<-0 to n-1)
{
println("Enter a player No,name and age")
var pno:Int=readInt()
var pname:String=readLine()
var age:Int=readInt()
println("Enter 1 for cricket player and 2 for football player :")
var choice:Int=readInt
if(choice==1)
{
println("Enter no.of innings,battings,bowling average:")
var noinnings=readInt
var batavg=readFloat
var balavg=readFloat
arr(i)=new CricketPlayer(pno,pname,age,noinnings,batavg,balavg)
}
else if(choice==2)
{
println("Enter no. of matches ,goals")
var no_matches=readInt
var goals=readInt
arr(i)=new FootBallPlayer(pno,pname,age,no_matches,goals)
}
}
println("Players name having batting average > 50")
for(i<-0 to n-1)
{
if(arr(i).getClass().getName().equals("CricketPlayer") &&
(arr(i).asInstanceOf[CricketPlayer]).getBatavg()>50)
println(arr(i).getPname)
}
println("Player names scoring more than 50 goals")
for(i<-0 to n-1)
{
if(arr(i).getClass().getName().equals("FootBallPlayer") &&
(arr(i).asInstanceOf[FootBallPlayer]).getgoals()>50)
println(arr(i).getPname)
}
}
}

Assignment 17 :
Write an abstract class Shape containing 3 data members of type dim1, dim2,
dim3 and three abstract method Area, Volume and Perimeter.Also define three
different subclasses CircleShape, RectangleShape, ConeShape containing the
implementation of abstract methods for all classes. Create object of three shapes
and call the appropriate method.

abstract class Shape(dim1:Float,dim2:Float,dim3:Float)


{
final var PI:Float=3.14f
def area():Float
def volume():Float
def perimeter():Float
}
class CircleShape(dim1:Float) extends Shape(dim1,0.0f,0.0f)
{
def area():Float=return(PI*dim1*dim1)
def volume():Float=return 0.0f
def perimeter():Float=return(2*PI*dim1)
}
class RectangleShape(dim1:Float,dim2:Float) extends Shape(dim1,dim2,0.0f)
{
def area():Float=return(dim1*dim2)
def volume():Float=return 0.0f
def perimeter():Float=return(2*(dim1+dim2))
}
class ConeShape(dim1:Float,dim2:Float,dim3:Float) extends
Shape(dim1,dim2,dim3)
{
def area():Float=return((PI*dim1*dim2)+(PI*dim1+dim2))
def volume():Float=return(0.33f*PI*dim1*dim2*dim3)
def perimeter():Float=return 0.0f
}
object Ass17
{
def main(args:Array[String])
{
var circle=new CircleShape(3.5f)
println("Area of Circle :"+circle.area())
println("Perimeter of Circle :"+circle.perimeter())
println("Volume of Circle :"+circle.volume())
var rectangle=new RectangleShape(2.3f,6.5f)
println("Area of Rectangle :"+rectangle.area())
println("Perimeter of Rectangle :"+rectangle.perimeter())
println("Volume of Rectangle :"+rectangle.volume())
var cone=new ConeShape(1.3f,3.2f,4.5f)
println("Area of Cone :"+cone.area())
println("Perimeter of Cone :"+cone.perimeter())
println("Volume of Cone :"+cone.volume())
}
}

Scala Trait
A trait is like an interface with a partial implementation. In scala, trait is a
collection of abstract and non-abstract methods. We can create trait that can
have all abstract methods or some abstract and some non-abstract methods.
A variable that is declared either by using val or var keyword in a trait get
internally implemented in the class that implements the trait. Any variable which
is declared by using val or var but not initialized is considered abstract.
Traits are compiled into Java interfaces with corresponding implementation
classes that hold any methods implemented in the traits.

Assignment 18 :
Write a scala program to create an trait Resizable with methods resizeWidth(int
width) and resizeHeight(int height) that allow an object to be resized. Create
anther trait Drawable with a method draw() that takes no arguments and returns
void. Create a class Rectangle that extends the Resizable and Drawable traits and
implements the abstract methods.

trait Resizable
{
def resizeWidth(width:Int):Unit
def resizeHeight(height:Int):Unit
}

trait Drawable
{
def draw()
}

class Rectangle extends Resizable with Drawable


{
private var height: Int=0
private var width : Int = 0
def this(height:Int,width:Int)
{
this()
this.height=height;
this.width=width;
}
override def toString():String=return s"\nHeight = "+height+"\nWidth = "+width;

def resizeWidth(width:Int)=this.width=width;

def resizeHeight(height:Int)= this.height=height;

def draw()=println("Rectangle is drawn.");

}
object Ass18
{
def main(args : Array[String])
{
var r=new Rectangle(23,12);
println("\nRectangle dimesion is \n"+r);
r.draw();
r.resizeWidth(45);
r.resizeHeight(15);
println("\nRectangle new dimesion is \n"+r);

}
}

List in scala :
Scala Lists are quite similar to arrays which means, all the elements of a list have
the same type but there are two important differences. First, lists are immutable,
which means elements of a list cannot be changed by assignment. Second, lists
represent a linked list whereas arrays are flat.
The type of a list that has elements of type T is written as List[T].

Tuples in scala :
Scala tuple combines a fixed number of items together so that they can be passed
around as a whole. Unlike an array or list, a tuple can hold objects with different
types but they are also immutable.

For e.g.
val t = (1, "hello", 12.5f) // 3 tuple elements – integer string and float
OR
val t = new Tuple3(1, "hello", 12.5f)
The actual type of a tuple depends upon the number and of elements it contains
and the types of those elements. Thus, the type of (99, "hello") is Tuple2[Int,
String]. The type of ('u', 'r', "the", 1, 4, "me") is Tuple6[Char, Char, String, Int, Int,
String]
Tuples are of type Tuple1, Tuple2, Tuple3 and so on. There currently is an upper
limit of 22 in the Scala if we need more, then we can use a collection, not a tuple.
For each TupleN type, where 1 <= N <= 22.
Scala defines a number of element-access methods. For e.g.
val t = (4,3,2,1)
To access elements of a tuple t, we can use method t._1 to access the first
element, t._2 to access the second, and so on. For example, the following
expression computes the sum of all elements of t.
val sum = t._1 + t._2 + t._3 + t._4

Scala Set :
Scala Set is a collection of pairwise different elements of the same type. In other
words, a Set is a collection that contains no duplicate elements. There are two
kinds of Sets, the immutable and the mutable. The difference between mutable
and immutable objects is that when an object is immutable, the object itself can't
be changed.
By default, Scala uses the immutable Set. If we want to use the mutable Set, we
have to import scala.collection.mutable.Set class explicitly. If we want to use
both mutable and immutable sets in the same collection, then we can continue to
refer to the immutable Set as Set but we can refer to the mutable Set
as mutable.Set.
// Empty set of integer type
var s : Set[Int] = Set()

// Set of integer type


var s : Set[Int] = Set(1,3,5,7)
or
var s = Set(1,3,5,7)

map in Scala :
Scala map is a collection of key/value pairs. Any value can be retrieved based on
its key. Keys are unique in the Map, but values need not be unique. Maps are also
called Hash tables. There are two kinds of Maps, the immutable and the mutable.
The difference between mutable and immutable objects is that when an object is
immutable, the object itself can't be changed.
By default, Scala uses the immutable Map. If we want to use the mutable Map,
we have to import scala.collection.mutable.Map class explicitly. If we want to use
both mutable and immutable Maps in the same, then we can continue to refer to
the immutable Map as Map but we can refer to the mutable set as mutable.Map.
The Following is the example statements to declare immutable Maps −
// Empty hash table whose keys are strings and values are integers:
var A:Map[Char,Int] = Map()

// A map with keys and values.


val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF")
While defining empty map, the type annotation is necessary as the system needs
to assign a concrete type to variable. If we want to add a key-value pair to a Map,
we can use the operator + as follows.
A + = ('I' -> 1)
A + = ('J' -> 5)
A + = ('K' -> 10)
A + = ('L' -> 100)

Assignment 19 :
Create Lists using five different methods( Lisp style , Java style, fill, range and
tabulate methods)
object Ass19
{
def main(args: Array[String])
{
println("Create a Scala List:")
println("Lisp style:")
val lisp_list = 100 :: 200 :: 300 :: Nil :: 400 :: Nil
println(lisp_list)
println("Java style:")
val nums = List(1,2,3,4,5,6,7)
println(nums)
println("Mixed type values in a list:")
val x = List[Number](100, 200, 110.20, 45d, 0x1)
println(x)
println("Range List:")
val y = List.range(1, 20)
println(y)
val z = List.range(0, 30, 3)
println(z)
println("Uniform List:")
val s = List.fill(5)("Scala")
println(s)
val n = List.fill(3)(4)
println(n)
println("Tabulate List:")
val t = List.tabulate(10)(n => n * n * n)
println(t)
}
}
Assignment 20 :

Create two Lists and Merge it and store the sorted in ascending order.

// Scala program to merge lists

// Creating object
object Ass20
{
// Main method
def main(args:Array[String])
{
// Creating Lists
val fruits = List("Mango", "Grapes", "Banana")
val flowers = List("Rose", "Lili", "Lotus", "Daisy")

// Merging Lists using ++


val list1 = fruits ++ flowers
println("After merging lists using :::, sorted list is ")
println(list1.sorted)

// Merging Lists using :::


val list2 = fruits ::: flowers
println("After merging lists using ::: , sorted in ascending order is ")
println(list2.sortWith(_ > _) ) // sort in ascending order

// Merging Lists using concat


val list3 = List.concat(fruits,flowers)
println("After merging lists using concat , sorted in descending order
is ")
println(list3.sortWith(_ > _) ) // sort in descending order
}
}

Assignment 21 :

Write a program to create two mutable sets and find common elements between
them.

import scala.collection.mutable.Set

object HelloWorld
{
def main(args: Array[String])
{

// Creating and initializing set


var set1 = Set(1,2,3,4)
var set2=Set(2,4,5,7)
// Adding new element in set using +=
set2 += 10

set2 ++== List(4,5,9,3) // 4 and 5 will not get added as duplicate value

set2.add(13)
set2.add(11)
println("\nSet2 after addition of new elements:")
println(set2)

println("Common elements are "+set1.intersect(set2))


}
}
Assignment 22 :

Write a user defined function to convert lowercase letter to uppercase and call
the function using Map.

import scala.io.StdIn.{readLine}

object Ass22
{
def lowerToUpper(ch:Char):Char=
{
if(ch.isLower)
return(ch.toByte-32).toChar
else
return ch
}

def main(args: Array[String])


{
println("Enter string ")
var str=readLine
var str1 = str.map(lowerToUpper)

println("Changed string is "+str1)


}
}

You might also like