1. Create a Person singleton and define a List in Person ((“xiaoming1″,”male”,18), (“xiaohua1″,”female”,20), (“xiaomeng”,”male” ,18), (“xiaoli1″,”female”,19), (“xiaoming2″,”male”,22), (“xiaoli2″,”female”,17), (“xiaoming4″,”male”,28 )
(1) Change everyone’s age to 3 times the previous one;
(2) Filter out those aged less than 20;
(3) Filter out women, especially women;
(4) Calculate the total age of everyone;
(5) Please sort by age from smallest to largest;
(6) Please sort by age from oldest to youngest;
(7) Combine each person’s name, gender, and age into one output;
(8) Separate people with odd and even ages
Program code:
object Person{<!-- --> def main(args:Array[String]): Unit = {<!-- --> var list = List(("xiaoming1","man",18),("xiaohua","woman",20),("xiaomeng","man",18),("xiaoli1","woman", 19),("xiaoming2","man",22),("xiaoli2","woman",17),("xiaoming4","man",28)) println() var res1 = list.map(a => List(a._1,a._2,a._3 * 3)) println(res1) println() var res2 = list.map(a => List(a._1,a._2,a._3 * 2 - 1)) println(res2) println() var res3 = list.filter(a => if(a._3 < 20) false else true) println(res3) println() var res4 = list.filter(a => if(a._3.equals( "woman")) false else true) println(res4) println() var res5 = list.map(a => a._3).reduce((a,b) => a + b) println(res5) println() list.sortBy(x => x._3).foreach(println) println() list.sortBy(x => -x._3).foreach(println) println() var res6 = list.map(a => a._1 + a._2 + a._3) println(res6) println() var res7 = list.partition({<!-- -->x =>x._3 % 2 == 0}) println(res7) } }
Run results:
2. Calculating series
Program to calculate and output the sum Sn of the first n terms of the following series until Sn is just greater than or equal to q, where q is an integer greater than 0, and its value is entered through the keyboard.
For example, if the value of q is 50.0, the output should be: Sn=50.416695. Test run in REPL mode, test sample: when q=1, Sn=2; when q=30, Sn=30.891459; when q=50, Sn=50.416695.
Program code:
import scala.io.StdIn._ import scala.util.control.Breaks._ import scala.util.{<!-- -->Try, Success, Failure} object project_two {<!-- --> def main(args: Array[String]): Unit = {<!-- --> breakable {<!-- --> //Through an infinite loop, add a loop control to realize the continuous input function while (true) {<!-- --> println("Please enter a positive integer:") println("Enter q or Q to exit...") //Because the data input from the keyboard includes various types, in order to increase fault tolerance, readLine() is selected val input = readLine() //Call the Try class to implement fault tolerance through pattern matching Try(input.toLong) match {<!-- --> //Determine whether the input value is a positive number case Success(q) if (q <= 0) => println("Please enter a positive integer greater than 0.") case Success(q) => try {<!-- --> //Implement the logic of series calculation var sn = 0.0 var n = 1 var an = 1.0 while (sn < q) {<!-- --> //Handle data overflow exceptions through the Math.addExact() function an = Math.addExact(n, 1) / n.toDouble sn = sn + an n = Math.addExact(n, 1) } printf("when q=%d, sn=%.6f",q,sn) println() } catch {<!-- --> //Handle the caught exception case _: ArithmeticException => println("An overflow exception occurred during calculation. Please try entering a smaller positive integer.") case _: Exception => println("An unknown exception occurred.") } //Implement program exit function case Failure(_: NumberFormatException) if input.equalsIgnoreCase("q") => println("The program has exited...") break //Exception handling case Failure(_: NumberFormatException) => println("Invalid input, please enter a valid positive integer or q to exit.") case Failure(exception) => println(s"An unknown exception occurred: ${<!-- -->exception.getMessage}") } } } } }
Run results:
3. Simulation graphics drawing
For a graphics drawing program, the following levels are used to abstract various entities. Define a Drawable trait, which includes a draw method, which is implemented by default to output a string representation of the object. Define a Point class to represent a point, which is mixed with the Drawable trait and contains a shift method for moving the point. The abstract class of all graphic entities is Shape, and its constructor includes a Point type, which represents the specific position of the graphic (the specific meaning is different for different specific graphics). The Shape class has a concrete method moveTo and an abstract method zoom, in which moveTo moves the graphic from the current position to a new position. The moveTo of various specific graphics may be different. The zoom method realizes the scaling of graphics and accepts a floating-point zoom factor parameter. The scaling implementation of different specific graphics is different. Specific graphic types that inherit the Shape class include the straight line class Line and the circle class Circle. The first parameter of the Line class represents its position, and the second parameter represents the other endpoint. When the Line is scaled, the position of its midpoint remains unchanged, and the length scales by multiples (note that when scaling, its two endpoint information also changes. ), in addition, Line’s move behavior affects another endpoint, and the move method needs to be overloaded. The first parameter of the Circle class represents its center, which is also its position, and the other parameter represents its radius. When the Circle is scaled, the position parameter remains unchanged and the radius is scaled by a multiple. In addition, both the straight line class Line and the circle class Circle are mixed with the Drawable trait, which requires overloading of draw. The information style of the draw output of the Line class is “Line: coordinates of the first endpoint – coordinates of the second endpoint)” , the information style output by the Circle-like draw is “Circle center: circle center coordinates, R=radius”. The following code has given the definitions of Drawable and Point, as well as the implementation of the program entry main function. Please complete the definitions of the Shape class, Line class and Circle class.
Program code:
//Simulate graphics drawing //All pictures are implemented using an interface trait Drawable{<!-- --> def draw():Unit={<!-- --> println(this.toString) } } //Create a point sample class. All graphics include points, and use a sample class to encapsulate the points. case class Point(var x:Double,var y:Double) extends Drawable{<!-- --> //Point movement method def shift(deltaX:Double,deltaY:Double)={<!-- --> x = x + deltaX y = y + deltaY } } //The parent class of all graphics is an abstract class abstract class Shape(var position:Point){<!-- --> //move def moveTo(newPosition:Point)={<!-- --> position = newPosition } //Telescopic def zoom(scaleFactor:Double):Unit override def toString: String = s"Shape:position($position)" } //straight line type class Line(start:Point,end:Point) extends Shape(start) with Drawable{<!-- --> //End point private var endPoint = end //move override def moveTo(newPosition:Point):Unit={<!-- --> val deltaX = newPosition.x-position.x val deltaY = newPosition.y - position.y super.moveTo(newPosition) endPoint.shift(deltaX,deltaY) } //Telescopic override def zoom(scaleFactor: Double): Unit = {<!-- --> val newEndX = position.x + (endPoint.x - position.x)*scaleFactor val newEndY = position.y + (endPoint.y - position.y)*scaleFactor endPoint = Point(newEndX,newEndY) } override def toString:String = s"Line:$position--$endPoint" } //Circle type class Circle(center:Point,radius:Double) extends Shape(center) with Drawable{<!-- --> private var circleRadius:Double=radius//radius //Telescopic def zoom(scaleFactor: Double): Unit = {<!-- --> circleRadius = circleRadius*scaleFactor } override def toString: String = s"Circle center:$position,R=$circleRadius" } object project_three {<!-- --> def main(args:Array[String])={<!-- --> try{<!-- --> //Create a point object val p = new Point(10,30) //output object p.draw() //Create a straight line object val line1 = new Line(Point(0,0),Point(20,20)) //Output the straight line object itself line1.draw() //Move the straight line to Point(5,5) line1.moveTo(Point(5,5)) //Output the position of the straight line object line1.draw() //Extend the straight line to twice its original length line1.zoom(2) //Output straight line object line1.draw() //Create a circle val cir = new Circle(Point(10,10),5) //output circle cir.draw() //Move to point (30, 20) cir.moveTo(Point(30,20)) //Output the parameters of the circle cir.draw() //Shrink to half of original size cir.zoom(0.5) //Output the parameters of the circle cir.draw() } catch {<!-- --> case ex:Exception => println(s"Exception is ${<!-- -->ex.getMessage}") } } }
Run results:
4. Create a single instance of ListOperation in ListOperation
(1) Create a List named list (6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 1, 2, 3, 4, 5 ) list
(2) Use map method and foreach method to traverse list
(3) Add the data in the set + 10 to generate a new list L2
(4) Take out all the even numbers in L2 to generate a new list L3
(5) Calculate the sum of L3 data
(6) Sort L3 in reverse order
(7)Reverse L3
(8) Create new list1 data as List(Array(11,22,33), Array(44,55,66))
(9) Use flatten to merge the list1 list into a new list
(10) Print the odd and even numbers in the list separately.
Program code:
object ListOperation{<!-- --> def main(args:Array[String]): Unit = {<!-- --> var list = List(6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,1,2,3,4,5) println() list.map(println) println() list.foreach(println) println() var L2 = list.map(_ + 10) L2.foreach(println) println() var L3 = L2.filter(x => if(x % 2 ==0) true else false) L3.foreach(println) println() println(L3.reduce((a,b) => a + b)) println() println(L3.sortBy(x => -x)) println() println(L3.reverse) println() var list1 = List(Array(11,22,33),Array(44,55,66)) list1.foreach(println) println() var list2 = list1.flatten list2.foreach(println) println() var list3 = list2.partition(x => x%2 == 0) list3._1.map(println) println() list3._2.map(println) } }
Run results: