Scala代码练习(复习用)
h4o3 2024-06-10 13:39:00 阅读 74
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)
}
}
声明
本文内容仅代表作者观点,或转载于其他网站,本站不以此文作为商业用途
如有涉及侵权,请联系本站进行删除
转载本站原创文章,请注明来源及作者。