Scala代码练习
1、编程实现百分制转换成五级制,规则如下:90~100分,返回优秀;
80~89分,返回良好;
70~79分,返回中等;
60~69分,返回及格;
60分以下,返回不及格。
object grade {
def main(args: Array): 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("不及格")
}
}
}11、定义一个函数为wrapHTML,添加前后缀(如和),传递部分参数,打印结果。
object whileTest {
def main(args: Array): Unit = {
var num=1
while(num<=50){
print(num+" ")
if(num%5==0){
println()
}
num+=1
}
}
}12、应用高阶函数,打印三角形;字符串数组,将其转成大写,再过滤掉以S开头的字符串。实现数字字符串的求和,如 Array("1,2", "3,4") 结果为10。
object jiujiu {
def main(args: Array): 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()
}
}
}13、编写函数values(fun:(Int)=>Int, low:Int, high:Int),该函数输出一个集合,对应给定区间内给定函数的输入和输出。例如,values(x=>x*x,-5,5)应该产生一个对偶的集合(-5,25),(-4,16),(-3,9),…,(5,25)。
class Rational(val x:Int=10,var y:Int,z:Int=20){
def sum():Int={
x+y+z
}
}
object Rational {
def main(args: Array): 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()}")
}
}15、创建内部类、内部对象以及匿名类,测试使用示例。
object Car {
def main(arg: Array) {
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)
}
}
}16、定义一个Logger测试构造器执行顺序造成空指针问题,两种解决方式。
object Student {
private val secrect1 = "i am secrect1 ******"
def accessCompanionClass(s: Student) = {
println(s"access Companion Class private field = ${s.secrect2}")
}
}
class Student {
private val secrect2 = "i am secrect2 *****"
def accessCompanionObject() = {
println(s"access Companion Object private field = ${Student.secrect1}")
}
}
object Runl {
def main(args: Array): Unit = {
Student.accessCompanionClass(new Student())
new Student().accessCompanionObject()
}
}17、设计一个Point类,其x和y坐标可以通过构造器提供,提供一个子类LabelPoint,其构造器接受一个标签值和x、y坐标,比如:
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): Unit = {
val p1=Point(3,4)
val sum1=p1.sum
print(sum1)
}
}18、提供一个cryptoLogger类,将日志消息以凯撒密码加密,默认密钥为3,不过使用者也可重新传值,提供默认密钥和-3作为密钥时的使用示例。
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): Unit = {
var a = new teacher("name1", "male1", "age1", "num1")
var b = new teacher("name2", "male2", "age2", "num1")
println(a.equals(b))
}
}21、使用不同方式定义可变和不可变数组及多维数组,测试添加元素、删除元素、清空等常用操作。
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): Unit = {
var a = new teacher("name1", "male1", "age1", "num1")
var b = new teacher("name2", "male2", "age2", "num1")
println(a.equals(b))
}
}24、测试Map键值对的相关操作,有查找映射的最大键或值,按键或值排序,按键或值过滤。
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): Unit = {
chuFa(3, 0)
}
}25、编写一个函数,接受一个字符串的集合,以及一个从字符串到整数值的映射。返回整型的集合,其值为能和集合中某个字符串相对应的映射的值。举例来说,给定Array ("Tom","Fred","Harry")和Map ("Tom"-> 3,"Dick"-> 4,"Harry"-> 5),返回Array(3,5)。提示:用flatMap将get返回的Option值组合在一起。
object RunWithParFuntion {
def main(args: Array): 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")
}
}26、测试Scala的模式匹配,模式数据类型有常量、变量、元组、序列、类型、构造器、变量绑定。
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): Unit = {
val p = new RunPartialFunction()
val htmlwithp = p.warpHTML("<p>", _: String, "<p>")
println("p=" + htmlwithp("i am p"))
val htmlwithdiv = p.warpHTML("", _: String, "")
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))
}
}27、在Scala中,利用List列表实现归并排序。
object RunHighFun {
def main(args: Array): 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")
}
}28、使用列表制作只在叶子节点存放值的树,举例来说,列表((3 8) 2 (5))描述的是如下这样一棵树,编写一个函数计算所有叶子节点中的元素之和。
+
/ | \
[*]2+
/\ |
38 5
object LowHigh {
def main(args: Array): 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))
}
}29、创建RunFunction.scala文件,进行隐式参数和隐式值的演练。
object findMaXdef {
def main(args: Array): 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 = {
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 = {
inputs.reduce((x, y) =>
if (fun(x) > fun(y))
x
else
y
)
}
}object RunNi {
def main(args: Array): 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)
}
}
}30、定义一个操作符+%,将一个给定的百分比添加到某个值,举例来说,120 +% 10应得到132。定义一个!操作符,计算某个整数的阶乘,举例来说,5!应得到120。提示:由于操作符是方法,而不是函数,使用隐式类来完成。
import java.io.PrintWriter
object RunFile {
def main(args: Array): 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"
}
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页:
[1]