Scala程式碼練習(複習用)

你这过氧化氢掺水了發表於2024-06-09

1、程式設計實現百分制轉換成五級制,規則如下:
90~100分,返回優秀;
80~89分,返回良好;
70~79分,返回中等;
60~69分,返回及格;
60分以下,返回不及格。

package main.scala.classStudy
object grade {
  def main(args: Array[String]): Unit = {
    val num = 70
    if(num>=90){
      println("優秀")
    }else if(num>=80){
      println("良好")
    }
    else if (num>=70) {
      println("中等")
    }
    else if (num>=60) {
      println("及格")
    }
    else if (num<60) {
      println("不及格")
    }
  }
}

2、使用while或do…while語句列印1~50,要求每行包含5個數,如下:

package main.scala.classStudy
object whileTest {
  def main(args: Array[String]): Unit = {
    var num=1
    while(num<=50){
      print(num+" ")
      if(num%5==0){
        println()
      }
      num+=1
    }
  }
}

3、使用for語句列印九九乘法表,執行結果如下:

package main.scala.classStudy
object jiujiu {
  def main(args: Array[String]): Unit = {
    var i=1
    while(i<=9){
      var j=1
      while(j<=i){
        var ans=i*j
        print(i+"*"+j+"="+ans+" ")
        j+=1
      }
      i+=1
      println()
    }
  }
}

4、定義Rational類,引數分別是要操作的三個有理數,要求:
(1)引數是Int;
(2)定義一個方法對引數求和;
(3)實現對指定的一個引數加10和20;

package main.scala.classStudy
class Rational(val x:Int=10,var y:Int,z:Int=20){
  def sum():Int={
    x+y+z
  }
}
object Rational {
  def main(args: Array[String]): Unit = {
    val r=new Rational(1,2,3)
    println(s"sum1=${r.sum()}")
    val r1=new Rational(y=1)
    println(s"sum2=${r1.sum()}")
    val r2=new Rational(5,y=1,10)
    println(s"sum3=${r2.sum()}")
  }
}

5、定義一個Car類,提供四組構造器,要求:
(1)只讀屬性:製造商、型號和年份;
(2)可讀寫屬性:車牌號;
(3)每一組構造器製造商和型號必填;
(4)年份和車牌號可選,如果未設定年份為-1,車牌為空字串。

object Car {
  def main(arg: Array[String]) {
    var car1 = new Car("BWM", "A6")
    car1.PrintAll()
    var car2 = new Car("BWM", "A6", 2000)
    car2.PrintAll()
    var car3 = new Car("BWM", "A6", "A01")
    car3.PrintAll()
    var car4 = new Car("BWM", "A6", 2000, "A01")
    car4.PrintAll()
  }
  class Car(val producerName: String, val productName: String, val productyear: Int, var num: String) {
    def this(producerName: String, productName: String) {
      this(producerName, productName, -1, "")
    }
    def this(producerName: String, productName: String, productyear: Int) {
      this(producerName, productName, productyear, "")
    }
    def this(producerName: String, productName: String, num: String) {
      this(producerName: String, productName: String, -1, num)
    }
    def PrintAll() {
      println("producerName:" + producerName + " productName:" + productName + " productyear:" + productyear + " num:" + num)
    }
  }
}

6、建立一個Student類和它的伴生物件,為Student類和它的伴生物件分別建立私有屬性secret,並相互訪問。

package main.scala.classStudy
class Student {
 private var secret="lll"
 println(Student.secret)
}
object Student{
 private var secret="mmm"
 def main(args: Array[String]): Unit = {
   var a =new Student
   println(a.secret)
 }
}

7、定義一個Point類和它的伴生物件,要求不使用new,而是用Point(3,4)建立物件,並求橫縱座標之和。

package main.scala.classStudy
class Point{
 var x=1
 var y=1
 def sum={
   x+y
 }
}
object Point{
//當物件(伴生物件)以函式的方式進行呼叫時,scala 會隱式地將呼叫改為在該物件上呼叫apply方法。
 def apply(x:Int,y:Int):Point = {
   var p = new Point()
   p.x=x
   p.y=y
   p
 }
}
object test{
 def main(args: Array[String]): Unit = {
   val p1=Point(3,4)
   val sum1=p1.sum
   print(sum1)
 }
}

8、定義一個Teacher類,包括名字、性別、年齡和職工號屬性,覆寫equals方法,滿足:
(1)若職工號相等,則認為兩個物件相等。
(2)所有屬性相等,則認為兩個物件相等。

package main.scala.classStudy
class teacher(val name:String,val male:String,val age:String,val num:String){
 def equals(obj:teacher):Boolean = {
  if(obj.num==this.num){
  true
  }else{
    false
  }
 }
}
object teacher{
 def main(args: Array[String]): Unit = {
   var a = new teacher("name1", "male1", "age1", "num1")
   var b = new teacher("name2", "male2", "age2", "num1")
   println(a.equals(b))
 }
}
package main.scala.classStudy
class teacher(val name:String,val male:String,val age:String,val num:String){
 def equals(obj: teacher): Boolean = {
   if (obj.name == this.name&&obj.male == this.male&&obj.age == this.age&&obj.num == this.num) {
     true
   } else {
     false
   }
 }
}
object teacher{
 def main(args: Array[String]): Unit = {
   var a = new teacher("name1", "male1", "age1", "num1")
   var b = new teacher("name2", "male2", "age2", "num1")
   println(a.equals(b))
 }
}

9、定義一個方法,對兩個整數相除,如果除數是0,則丟擲 “can not divide by zero”異常。

package main.scala.classStudy
object zero {
 def chuFa(a: Int, b: Int): Unit = {
   if (b == 0) {
     println("can not divide by zero")
   }
   else {
     println(a / b)
   }
 }
 def main(args: Array[String]): Unit = {
   chuFa(3, 0)
 }
}

10、定義一個exeAdd函式,接受一個帶有整型引數的函式,對整數加10。定義一個exeAndPrint方法,接受一個帶兩個引數的函式和兩個整型,將整型引數賦予函式,計算列印結果。

package main.scala.classStudy
object RunWithParFuntion {
 def main(args: Array[String]): Unit = {
   val sayhello = () => {
     print("hello scala function")
   }
   exeFuctionWithOutPar(sayhello)
   val plusTen = (i: Int) => {
     i + 10
   }
   exeAdd(plusTen)
   val sum = (x: Int, y: Int) => x + y
   val multi = (x: Int, y: Int) => x * y
   exeAndPrint(sum, 2, 3)
   exeAndPrint(multi, 2, 3)
 }
 def exeFuctionWithOutPar(callback: () => Unit): Unit = {
   callback()
 }
 def exeAdd(callback: Int => Int): Int = {
   callback(8)
 }
 def exeAndPrint(callback: (Int, Int) => Int, x: Int, y: Int): Unit = {
   val result = callback(x, y)
   println(s"callback=$result")
 }
}

11、定義一個函式為wrapHTML,新增前字尾(如<div>和</div>),傳遞部分引數,列印結果。

package main.scala.classStudy
class RunPartialFunction {
 def warpHTML(pref: String, context: String, suffix: String): String = {
   pref + context + suffix
 }
 def mutlti(x: Int, y: Int, z: Int) = x * y * z
}
object RunPartialFunction {
 def main(args: Array[String]): Unit = {
   val p = new RunPartialFunction()
   val htmlwithp = p.warpHTML("<p>", _: String, "<p>")
   println("p=" + htmlwithp("i am p"))
   val htmlwithdiv = p.warpHTML("<div>", _: String, "<div>")
   println("div=" + htmlwithdiv("i am div"))
   val f1 = p.mutlti(_: Int, 2, _: Int)
   println(f1(4, 5))
   val f2 = p.mutlti(_: Int, 2, 3)
   println(f2(5))
   val f3 = p.mutlti(_: Int, _: Int, _: Int)
   println(f3(5, 1, 2))
 }
}

12、應用高階函式,列印三角形;字串陣列,將其轉成大寫,再過濾掉以S開頭的字串。實現數字字串的求和,如 Array("1,2", "3,4") 結果為10。

package main.scala.classStudy
object RunHighFun {
 def main(args: Array[String]): Unit = {
   val array = Array(1, 2, 3, 4, 5)
   val s = array.map(x => "*" * x)
   array.map("*" * _).foreach(println(_))
   val s2 = Array("scala", "java", "spark")
   s2.map(x => x.toUpperCase).filter(s => (!s.startsWith("S"))).foreach(println(_))
   val sumarrary = Array("1,2", "3,4")
   val sum = sumarrary.flatMap(x => x.split(",")).map(_.toInt).reduce(_ + _)
   println(s"sum=$sum")
 }
}

13、編寫函式values(fun:(Int)=>Int, low:Int, high:Int),該函式輸出一個集合,對應給定區間內給定函式的輸入和輸出。例如,values(x=>x*x,-5,5)應該產生一個對偶的集合(-5,25),(-4,16),(-3,9),…,(5,25)。

package main.scala.classStudy
object LowHigh {
 def main(args: Array[String]): Unit = {
   val f = (x: Int) => x * x
   val result = values(f, -5, 5)
   result.foreach(println(_))
 }
 def values(fun: (Int) => Int, low: Int, high: Int): IndexedSeq[(Int, Int)] = {
   for (i <- low to high) yield (i, fun(i))
 }
}

14、編寫函式largest(fun:(Int)=>Int, inputs:Seq[Int]),輸出在給定輸入序列中給定函式的最大值。例如,largest(x=>10x-xx,1 to 10)應該返回25。要求不得使用迴圈或遞迴。

package main.scala.classStudy
object findMaXdef {
 def main(args: Array[String]): Unit = {
   val f = (x: Int) => 10 * x - x * x
   val maxValue = largestValue(f, 1 to 10)
   println(s"maxValue=$maxValue")
   val maxIndex = largestIndex(f, 1 to 10)
   println(s"maxIndex=$maxIndex")
 }
 def largestValue(fun: (Int) => Int, inputs: Seq[Int]): Int = {
   val result = inputs.map(x => fun(x))
   result.reduce((x, y) =>
     if (x > y)
       x
     else
       y
   )
 }
 def largestIndex(fun: (Int) => Int, inputs: Seq[Int]): Int = {
   inputs.reduce((x, y) =>
     if (fun(x) > fun(y))
       x
     else
       y
   )
 }
}

15、建立內部類、內部物件以及匿名類,測試使用示例。

package main.scala.classStudy
object RunNi {
 def main(args: Array[String]): Unit = {
   val p1 = new P("jason", 10) {
     override def print(): Unit = {
       println(s"P($name,$age)")
     }
   }
   p1.print
   println("------------------------------------------")
   val s = new StudentIntenal("scala", 5)
   val grade = new s.Grade("1 grade")
   println(s"grade=${grade.name}")
   s.Uilts1.print("vtil1")
   StudentIntenal.Uilts2.print("util2")
   val pr = new StudentIntenal.printer
   pr.print("printer")
 }
}
abstract class P(var name: String, var age: Int) {
 def print
}
class StudentIntenal(var name: String, var age: Int) {
 class Grade(var name: String)
 object Uilts1 {
   def print(name: String) = {
     println(name)
   }
 }
}
object StudentIntenal {
 class printer {
   def print(name: String) = {
     println(name)
   }
 }
 object Uilts2 {
   def print(name: String) = {
     println(name)
   }
 }
}

16、定義一個Logger測試構造器執行順序造成空指標問題,兩種解決方式。

import java.io.PrintWriter
object RunFile {
 def main(args: Array[String]): Unit = {
   val p = new {
     override val filename = "p052.log"
   }
     with Person051
   p.log("Person052 create log")
 }
}
trait Logger {
 def log(msg: String)
}
trait FileLogger extends Logger {
 val filename: String
 val fileout = new PrintWriter(filename)
 def log(msg: String) = {
   fileout.println(msg)
   fileout.flush()
 }
}
class Person051 extends FileLogger {
 override val filename = "p051.log"
}

17、設計一個Point類,其x和y座標可以透過構造器提供,提供一個子類LabelPoint,其構造器接受一個標籤值和x、y座標,比如:

New LabelPoint(“black”, 1929, 230.07)
package main.scala.classStudy
object Lpoint {
 def main(args: Array[String]): Unit = {
   val lp = new LabelPoint("black", 1929, 230.07)
   println(s"lp.label=${lp.label},lp.x=${lp.x},lp.y=${lp.y}")
 }
}
class Point05(val x: Double, val y: Double) {
 println(s"parent=>x=$x,y=$y")
}
class LabelPoint(val label: String, x: Double, y: Double) extends Point05(x, y) {
 println(s"child=>label=$label,=>x=$x,y=$y")
}

18、提供一個cryptoLogger類,將日誌訊息以凱撒密碼加密,預設金鑰為3,不過使用者也可重新傳值,提供預設金鑰和-3作為金鑰時的使用示例。

package main.scala.classStudy
trait Logger {
 def log(str: String, key: Int)
}
class cryptoLogger extends Logger {
 override def log(str: String, key: Int=3): Unit = {
   println(for(i<-str)yield (97+(i-97+key+(if(key<0) 26 else 0))%26).toChar)
 }
}
object RunCrypto {
 def main(args: Array[String]): Unit = {
   new cryptoLogger().log("abc")
   new cryptoLogger().log("abc",-3)
   new cryptoLogger().log("xyz")
   new cryptoLogger().log("xyz",-3)
 }
}

19、定義一個抽象類Item,加入方法price和description,SimpleItem是一個在構造器中給出價格和描述的物件。Bundle是一個可以包含其他物件的物件,其價格是打包中所有物件的價格之和,同時提供一個將物件新增到打包中的機制,以及一個合適的description方法。

package main.scala.classStudy
class SimpleItem(var p: Double, var desc: String) extends Item {
 def price: Double = p
 def description: String = desc
}
class Bundle(var items: Array[SimpleItem]) extends Item {
 def price: Double = {
   var p = 0.0
   items.foreach(p += _.price)
   p
 }
 def description: String = {
   var desc = ""
   items.foreach(desc += _.description)
   desc
 }
}
object RunItem {
 def main(args: Array[String]): Unit = {
   val s1 = new SimpleItem(12.5, "apple")
   val s2 = new SimpleItem(24.8, "banana")
   val s3 = new SimpleItem(9.9, "orange")
   val fruits = new Bundle(Array(s1, s2, s3))
   println(s"price=${fruits.price},description=${fruits.description}")
 }
}
abstract class Item {
 def price: Double
 def description: String
}

20、測試迭代器的常用方法,有it.next()、it.hasNext、it.duplicate、it.slice(m,n)、it.zip()、it.zipAll()等。

package main.scala.classStudy
object RunIterator {
 def main(args: Array[String]): Unit = { //1.Range
   val it1 = Iterator(1 to 5)
   println(it1.hasNext, it1.next())
   val it2 = Iterator(1, 2, 3)
   println(it2.hasNext, it2.next())
   println(it2.hasNext, it2.next())
   println(it2.hasNext, it2.next()) //Iterator(1,2,3,4,5,6,7,8,9,10)
   val it3 = Iterator(1 to 5: _*)
   while (it3.hasNext) {
     println(it3.next())
   }
   val it4 = Iterator(1 to 3: _*)
   it4.foreach(x => println(x))
   it4.foreach(x => println(x))
   val it5 = Iterator(6 to 8: _*)
   val (it51, it52) = it5.duplicate
   it5.foreach(x => println(x))
   it52.foreach(x => println(x))
   it5.foreach(x => println(x))
   val it6 = Iterator(9 to 12: _*)
   val it61 = it6.take(2)
   it61.foreach(x => println("it61=" + x))
   it6.foreach(x => println("it6=" + x))
   val it7 = Iterator(13 to 18: _*)
   val it71 = it7.slice(1, 10)
   it71.foreach(x => println("it71=" + x))
   val it8key1 = Iterator("kl", "k2")
   val it8v1 = Iterator("v1", "v2")
   val it8v2 = Iterator("v1")
   val it8k2 = Iterator("k1")
   //      val k1_v1=it8key1.zip(it8v1)
   //      k1_v1.foreach(x => println(x))
   //      val k1_v2 = it8key1.zip(it8v2)
   //      k1_v2.foreach(x => println(x))
   //      val k1_v2 = it8key1.zipAll(it8v2, "default1", "default2")
   //      11 k1_v2.foreach(x => println(x))
   val k2_v1 = it8k2.zipAll(it8v1, "default1", "default2")
   k2_v1.foreach(x => println(x))
 }
}

21、使用不同方式定義可變和不可變陣列及多維陣列,測試新增元素、刪除元素、清空等常用操作。

package main.scala.classStudy
import scala.collection.mutable.ArrayBuffer
object RunArray {
 def main(args: Array[String]): Unit = {
   val arr1 = new Array[Int](3)
   val arr2 = Array(1, 2d, 31)
   arr2.foreach(println(_))
   val arr3 = Array[Number](1, 2d, 31)
   arr3.foreach(println(_))
   arr1(0) = 7
   arr2(1) = 8
   arr3(2) = 9
   arr1.foreach(x => println(x + ","))
   val r1 = Array.range(1, 5)
   val r3 = Array.fill(2)("scala")
   val r4 = List("a", "b").toArray
   val r5 = Array.tabulate(3)(n => n * n)
   r1.foreach(x => println("r1=" + x + ","))
   println()
   r3.foreach(x => println("r3=" + x + ","))
   println()
   r4.foreach(x => println("r4=" + x + ","))
   println()
   r5.foreach(x => println("r5=" + x + ","))
   println()
 }
 val ab1 = ArrayBuffer(1, 2, 3)
 val ab2 = new ArrayBuffer[String](1)
 ab2 += "a"
 ab2 += "b"
 ab2 ++= Seq("s1", "s2")
 ab2.append("apend1")
 println(s"before=$ab2")
 ab2 -= "b"
 ab2 --= Seq("s1", "s2")
 ab2.remove(0)
 ab2.append("apend4", "apend3", "apend2")
 ab2.remove(1, 3)
 ab2.clear
 println(s"after=$ab2")
 val arr7 = Array[String]("banana", "apple")
 val arr8 = arr7.filter(x => x.startsWith("b"))
 arr8.foreach(x => print("arr7=" + x + ","))
 val marr1 = Array.ofDim[String](2, 2)
 marr1(0)(0) = "a"
 marr1(0)(1) = "b"
 marr1(1)(0) = "c"
 marr1(1)(1) = "d"
 for {
   i <- 0 until 2
   j <- 0 until 2
 } {
   println(s"($i,$j)=${marr1(i)(j)}")
   var marr2 = Array(Array(1, 2), Array(3, 4))
   println(marr2(1)(0))
   marr2 ++= Array(Array(5, 6))
   println(marr2(2)(1))
 }
}

22、透過Nil和::方式構建List列表,測試合併操作、懶載入、zipped操作、摺疊操作等。

package main.scala.classStudy
import scala.collection.mutable.ListBuffer
object RunList {
 def main(args: Array[String]): Unit = {
   //lsit(1,2,3)
   var l1 = 1 :: 2 :: 3 :: Nil
   println(s"l1,head=${l1.head},list(2)=${l1(2)}")
   val l2 = List(4, 5, 6)
   val l3 = l2 :: l1
   println(l3)
   //++,concat
   val l4 = l2 :: l1
   println(l4)
   val lb1 = ListBuffer(7, 8, 9)
   lb1(0) = 99
   println(lb1)
   val s = 1 #:: 2 #:: 3 #:: Stream.empty
   val s2 = s.map(x => x + 1)
   println(s2, s2(2))
   println(s.force)
   val zip1 = (List(1, 2), List(3, 4, 5)).zipped.map(_ * _)
   println(s"zip1=$zip1")
   val words = List("scala", "is", "good")
   val s3 = (" " /: words)(_ + " " + _)
   println(s3)
   val s4 = (words.head /: words.tail)(_ + " " + _)
   println(s4)
 }
}

23、測試Set集合的常用操作,有條件操作、加法、減法、二元邏輯操作、更新等,對於自定義類實現比較方法並排序。

package main.scala.classStudy
import scala.collection.{SortedSet, mutable}
object RunSet {
 def main(args: Array[String]): Unit = {
   val s1 = Set(1, 2, 3, 3, 2, 5)
   val s2 = Set(3, 5)
   val s3 = Set(4, 5)
   println(s1)
   println(s1.contains(1), s1.contains(6))
   println(s1(2), s1(8))
   println(s"s1 sub s2 ${s1.subsetOf(s2)}")
   println(s"s1 sub s3 ${s1.subsetOf(s3)}")
   println(s"s2 sub s1 ${s1.subsetOf(s1)}")
   println(s"s3 sub s1 ${s1.subsetOf(s1)}")
   var imms = Set(4, 5, 6)
   val imm1 = imms + 3
   val imm2 = imm1 + (22, 33)
   val imm3 = imm2 ++ List(44, 55)
   println(imm3)
   println(imms)
   var ms = scala.collection.mutable.Set(7, 8, 9)
   ms += 10
   ms += (11, 12, 12)
   ms ++= Set(13, 14)
   println(ms)
   ms.retain(_ > 9)
   ms.remove(12)
   ms.clear
   println(ms)
   val ss1 = mutable.SortedSet(10, 3, 11, 2)
   val ss3 = SortedSet(7, 3, 11)
   println(ss1)
   println(ss3)
   val ss2 = mutable.SortedSet("banana", "apple")
   println(ss2)
   val lhs = mutable.LinkedHashSet(1, 8, 4)
   println(lhs)
   val p1 = new Person0701("scala", 12)
   val p2 = new Person0701("java", 2)
   val p3 = new Person0701("c", 20)
   val p = mutable.SortedSet(p1, p2, p3)
   println(p)
 }
}
class Person0701(var name: String, var age: Int) extends Ordered[Person0701] {
 override def compare(that: Person0701): Int = {
   if (this.age == that.age) {
     0
   }
   else if (this.age < that.age) 1
   else -1
 }
}

24、測試Map鍵值對的相關操作,有查詢對映的最大鍵或值,按鍵或值排序,按鍵或值過濾。

package main.scala.classStudy
import scala.collection.mutable
object RunMap {
 def main(aegs: Array[String]): Unit = {
   val mp = mutable.Map(1 -> "a", 2 -> "b", 3 -> "c")
   mp.retain((k, v) => k > 2)
   println(s"mp=$mp")
   val m = mutable.Map(4 -> "d", 5 -> "e", 6 -> "f")
   val m1 = m.filterKeys(_ > 4)
   println(s"m1=$m1")
   val m2 = m.filterKeys(Set(4, 6))
   println(s"m2=$m2")
   val m3 = m.filter(x => x._1 > 5)
   println(s"m3=$m3")
   val mm = mutable.Map("ab" -> 12, "e" -> 4, "byyy" -> 99, "muuuuuu" -> 17)
   val mm1 = mm.max
   val min1 = mm.min
   println(s"max1=$mm1,min1=$min1")
   val minv = mm.valuesIterator.min
   val maxv = mm.valuesIterator.max
   println(s"minv=$minv,maxv=$maxv")
   val mink = mm.keysIterator.min
   val maxk = mm.keysIterator.max
   println(s"mink=$mink,maxk=$maxk")
   val result = mm.keysIterator.reduceLeft((x, y) => if (x.length > y.length) x else y)
   println(s"result=${result}")
   val sq1 = mm.toSeq.sortBy(_._1)
   val sq2 = mm.toSeq.sortBy(_._2)
   println(s"sq1=$sq1")
   println(s"sq2=$sq2")
   println(sq1.toMap)
   println(sq2.toMap)
   val sq3 = mm.toSeq.sortWith(_._2 > _._2)
   println(s"sq3=$sq3")
   println(sq3.toMap)
 }
}

25、編寫一個函式,接受一個字串的集合,以及一個從字串到整數值的對映。返回整型的集合,其值為能和集合中某個字串相對應的對映的值。舉例來說,給定Array ("Tom","Fred","Harry")和Map ("Tom"-> 3,"Dick"-> 4,"Harry"-> 5),返回Array(3,5)。提示:用flatMap將get返回的Option值組合在一起。

package main.scala.classStudy
object Run07 {
 def main(args: Array[String]): Unit = {
   val arr = Array("tom", "fred", "harry")
   val mp = Map("tom" -> 3, "dick" -> 4, "harry" -> 5)
   println(fun2(arr, mp))
 }
 def fun2(input1: Seq[String], input2: Map[String, Int]): Seq[Int] = {
   input1.map(key => input2.getOrElse(key, 0)).filter(value => value != 0)
 }
}

相關文章