Experiment 2 - primary practice of scala programming - topic

1. Calculation series

Please program, calculate and output the sum Sn of the first n items of the following series in the form of script until Sn is just greater than or equal to Q, where q is an integer greater than 0, and its value is input through the keyboard.

 

 

 

For example, if the value of q is 50.0, the output should be: Sn=50.416695. Please save the source file as exercise2-1 Scala, test run in REPL mode,

Test example: when q=1, Sn=2; When q=30, Sn=30.891459; When q=50, Sn=50.416695.

import scala.io.StdIn

object sy1 {
  def main(args: Array[String]): Unit = {
    var p = StdIn.readInt()
    var s: Float = 0
    var n: Float = 1
    while (s<p){
      s=s+(n+1)/n
      n=n+1
    }
    println(s"Sn=${s}")
  }
}

Run in the command line terminal, first create sy2. 0 in the folder drawn below Scala file, copy the above code into the file, and then directly enter scala sy2 under Windows cmd or linux terminal Scala is ready to run

 

2. Simulation drawing

 

 

For a graphics rendering program, the following levels are used to abstract various entities. Define the characteristics of a Drawable, which includes a draw method, which is implemented as the string representation of the output object by default. Define a Point class to represent points, which is mixed with Drawable characteristics, and contains a shift method for moving points. The abstract class of all graphic entities is Shape, and its constructor includes a Point type to represent the specific location 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. moveTo moves the graph from the current position to a new position. The moveTo of various concrete graphs may be different. Zoom method realizes the zoom of graphics and accepts a floating-Point zoom multiple parameter. The zoom implementation is different for different specific graphics. The specific Shape types that inherit the Shape class include Line class and Circle class. The first parameter of the Line class represents its position, and the second parameter represents another endpoint. When the Line is zoomed, the position of the Point remains unchanged, and the length is zoomed by multiple (note that the information of the two endpoints is also changed when zooming). In addition, the move behavior of the Line affects the other endpoint, so the move method needs to be overloaded. The first parameter of Circle class represents its center and position, and the other parameter represents its radius. When Circle is scaled, the position parameter remains unchanged, and the radius is scaled by multiple. In addition, the straight Line class Line and the Circle class Circle are mixed with the Drawable feature, which requires the overload implementation of the draw. The information style of the draw output of the Line class is "Line: coordinates of the first endpoint -- coordinates of the second endpoint", and the information style of the draw output of the Circle class is "Circle center: coordinates of the center of the Circle, 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 Shape class, Line class and Circle class.

//Idiosyncrasy
trait Drawable { def draw(): Unit
={ println(this.toString) } } //Shape class abstract class Shape(var point:Point) { def moveTo(changePoint: Point)= { point = changePoint } def zoom(float: Float) }
//Point class
case class Point(var x:Double,var y:Double) extends Drawable { def shift(deltaX:Double,deltaY:Double): Unit ={ x+=deltaX y+=deltaY } }
//Circle class
//Why can't the parameters of the child class be the same as the name of the parent classindividualpoint1 All modified to point Unexpected results will occur class Circle( point1: Point, var r:Float) extends Shape(point1) with Drawable { override def zoom(float: Float) { r = r*float } override def draw(): Unit = { println(s"Circle center:(${point.x},${point.y}),R=$r") } }
//Line class
class Line(var startPoint:Point,var endPoint:Point) extends Shape(startPoint) with Drawable { override def moveTo(changePoint: Point){ val changeX = changePoint.x - startPoint.x val changeY = changePoint.y - startPoint.y startPoint = changePoint endPoint.x = endPoint.x+changeX endPoint.y = endPoint.y+changeY } def zoom(float: Float): Unit ={ var centerX = (startPoint.x+endPoint.x)/2 var centerY = (startPoint.y+endPoint.y)/2 var absXDiv2 = (startPoint.x-endPoint.x).abs/2 var absYDiv2 = (startPoint.y-endPoint.y).abs/2 if((startPoint.x-endPoint.x)>0){ startPoint.x = centerX+ float*absXDiv2 endPoint.x = centerX - float*absXDiv2 }else{ endPoint.x = centerX + float*absXDiv2 startPoint.x = centerX - float*absXDiv2 } if((startPoint.y - endPoint.y)>0){ startPoint.y = centerY+float*absYDiv2 endPoint.y = centerY-float*absYDiv2 }else{ endPoint.y = centerY+float*absYDiv2 startPoint.y = centerY - float*absYDiv2 } } override def draw(): Unit ={ println(s"Line:$startPoint--$endPoint") } }
//Test class object MyDraw { def main(args: Array[String]): Unit
= { val p=new Point(10,30) p.draw; val line1 = new Line(Point(0,0),Point(20,20)) line1.draw line1.moveTo(Point(5,5)) //Move to a new point line1.draw line1.zoom(2) //Zoom in twice line1.draw val cir= new Circle(Point(10,10),5) cir.draw cir.moveTo(Point(30,20)) cir.draw cir.zoom(0.5f) cir.draw } }

Operation results:

 

 

 

 

3. Statistics of student achievement

 

I think this topic is difficult and I don't fully understand the following procedures

 

 

 

 

 

object test2 {
  def main(args: Array[String]): Unit = {
    val inputFile = Source.fromFile("test/test1.txt")
    //"\\s+"Is a string regular expression. Press blank on each line(Include spaces/Tab)separate
    //Since multiple traversals may be involved, the same as tolist take Iterator pretend List
    val originalData = inputFile.getLines().map{_.split("\\s+")}.toList
    val courseNames = originalData.head.drop(2)//Get the course name in the first row
    println(courseNames.toList)
    val allStudents = originalData.tail//Remove the first row of data
    val courseNum = courseNames.length
    //Statistics function. The parameter is the required common statistics line
    //External variables are used courseNum,It belongs to closure function
    def statistc(lines:List[Array[String]]) ={
      //for The derivation generates a triple for each course, representing the total score, the lowest score and the highest score respectively
      (for(i<-2 to courseNum+1) yield{
        //Take out the columns to be counted
        val temp = lines map { elem => elem(i).toDouble }
        (temp.sum,temp.min,temp.max)
        }) map{case (total,min,max) => (total/lines.length,min,max)
      }//the last one map yes for The total score is changed to the average score
    }
    //Output results
    def printResult(theresult:Seq[(Double,Double,Double)]): Unit ={
      //Call before traversing zip Method combines the course name container and the result container, and the combined result is a binary container
      (courseNames zip theresult) foreach{
        case (course,result)=>
          println(f"${course+":s"}%-10s${result._1}%5.2f${result._2}%8.2f${result._3}%8.2f")
      }
    }
    //Call two functions respectively to count all students and output the results
    val allResult = statistc(allStudents)
    println("course average min max")
    printResult(allResult)

    //Divided into two containers by gender
    val (maleLines,femaleLines) = allStudents partition
    {_(1)=="male"}
    //Call two functions respectively to count male students and output the results
    val maleResult = statistc(maleLines)
    println("course average min max")
    printResult(maleResult)
    // Call two functions respectively to count male students and output the results
    val femaleResult = statistc(femaleLines)
    println("course average min max")
    printResult(femaleResult)
  }
}

Operation results:

 

Keywords: Scala

Added by techrat on Mon, 17 Jan 2022 05:39:21 +0200