Scala练习代码合集
1.
-
作业

1 object title1 { 2 def main(args: Array[String]): Unit = { 3 isPalindrom("dad") 4 isPalindrom("henry") 5 } 6 def isPalindrom(word:String): Unit ={ 7 if(word.equals(word.reverse)) { 8 println(word+"是回文单词") 9 } else{ 10 println(word+"不是回文单词") 11 } 12 } 13 14 }

1 object title2 { 2 def main(args: Array[String]): Unit = { 3 narcissus() 4 } 5 6 def narcissus(): Unit = { 7 for (number <- 100 to 999) { 8 val a = number / 100 9 val b = number % 100 / 10 10 val c = number % 100 % 10 11 if (a * a * a + b * b * b + c * c * c == number) { 12 print(number + ",") 13 } 14 } 15 }

1 object title3 { 2 def main(args: Array[String]): Unit = { 3 println("x < 0,y的值为:\n" + func(-1)) 4 println("x == 0,y的值为:\n"+ func(0)) 5 println("x > 0,y的值为:\n"+ func(2)) 6 } 7 8 def func(x: Int): Int = { 9 var y = 0 10 if (x < 0) y = x * x + 1 11 if (x == 0) y = 2 12 if (x > 0) y = 6 * x + 3 13 return y 14 } 15 16 }

1 object test1 { 2 def main(args: Array[String]): Unit = { 3 val numList = List(8,0,0,1,3,1,0) 4 matchTest(numList) 5 } 6 def matchTest(x:List[Int]):Unit = x match { 7 case List(0,_*)=>println("头部为0的列表") 8 case x if x.last == 0=>println("尾部为0的列表") 9 case List(_,0,_*)=>println("第二个元素为0的列表") 10 case _=>println("其他情况") 11 } 12 13 }

1 object test2 { 2 def main(args: Array[String]): Unit = { 3 val sentence = "Get Spark from the downloads page of the project website. This documentation is for Spark version 2.4.5. Spark uses Hadoop’s client libraries for HDFS and YARN. Downloads are pre-packaged for a handful of popular Hadoop versions. Users can also download a “Hadoop free” binary and run Spark with any Hadoop version by augmenting Spark’s classpath. Scala and Java users can include Spark in their projects using its Maven coordinates and in the future Python users can also install Spark from PyPI." 4 val new_sentence = sentence.split(" ") // 以空格为分割 5 var count = 0 //初始化计数器为0 6 for(x<-new_sentence){ //遍历分割后的数据 7 if(x.contains("Spark")) 8 count +=1 // 若包含Spark,则计数器+1 9 } 10 println("这段话中出现\"Spark\"单词的次数为:\n" + count) 11 } 12 13 }

1 object test3 { 2 def main(args: Array[String]): Unit = { 3 val myList = List(135, 120, 520) 4 matchTest(myList) 5 } 6 7 def matchTest(x: List[Int]): Unit = x match { 8 case x if x.head % 2 == 0 => println("头部为偶数的列表") 9 case x if x.head == x.last && x.length >= 2 => println("头部相等的列表") 10 case List(_, _, _) if x(0) > 99 && x(1) > 99 && x(2) > 99 => println("3位数俱乐部") 11 case _ => println("一般列表") 12 } 13 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库