scala语言写一个简单鲜花代码
时间: 2023-07-16 14:14:55 浏览: 83
以下是一个简单的 Scala 代码,演示如何创建一个鲜花类和使用它:
```scala
class Flower(val name: String, val color: String) {
def bloom(): Unit = {
println(s"A $color $name is blooming.")
}
}
val rose = new Flower("rose", "red")
rose.bloom() // 输出 "A red rose is blooming."
```
在这个例子中,我们定义了一个 `Flower` 类,并在类中定义了两个属性 `name` 和 `color`,以及一个 `bloom` 方法来描述鲜花开放的过程。然后我们创建了一个 `rose` 对象,并调用它的 `bloom` 方法。
输出结果是 "A red rose is blooming.",说明我们成功地创建了一个鲜花对象并调用了它的方法。
相关问题
利用scala语言写一个wordcount
好的,下面是一个简单的Scala代码实现Word Count:
```scala
import scala.io.Source
object WordCount {
def main(args: Array[String]) {
val filename = args(0)
val source = Source.fromFile(filename)
val lines = source.getLines().toList
source.close()
// 使用flatMap和split方法将所有单词展开成一个List
val words = lines.flatMap(_.split("\\W+"))
// 使用groupBy方法将相同的单词分组,并使用mapValues方法计算每个单词的数量
val wordCount = words.groupBy(identity).mapValues(_.length)
// 将结果按照单词数量倒序排列并打印输出
wordCount.toSeq.sortWith(_._2 > _._2).foreach {
case (word, count) => println(s"$word: $count")
}
}
}
```
说明:
1. 代码首先读取命令行参数中的文件名,并使用Scala的`Source`类从文件中读取所有行,并将它们存储在一个列表中。
2. 使用`flatMap`和`split`方法将所有行分成单个单词,并将它们展开成一个列表。
3. 使用`groupBy`方法将相同的单词分组,并使用`mapValues`方法计算每个单词的数量。
4. 将结果按照单词数量倒序排列,并使用`foreach`方法打印输出。
用Scala语言写一个九九乘法表
以下是用Scala语言写的九九乘法表代码:
```scala
for(i <- 1 to 9; j <- 1 to i) {
print(s"$j * $i = ${i * j}\t")
if(i == j) println()
}
```
输出结果如下:
```
1 * 1 = 1
1 * 2 = 2 2 * 2 = 4
1 * 3 = 3 2 * 3 = 6 3 * 3 = 9
1 * 4 = 4 2 * 4 = 8 3 * 4 = 12 4 * 4 = 16
1 * 5 = 5 2 * 5 = 10 3 * 5 = 15 4 * 5 = 20 5 * 5 = 25
1 * 6 = 6 2 * 6 = 12 3 * 6 = 18 4 * 6 = 24 5 * 6 = 30 6 * 6 = 36
1 * 7 = 7 2 * 7 = 14 3 * 7 = 21 4 * 7 = 28 5 * 7 = 35 6 * 7 = 42 7 * 7 = 49
1 * 8 = 8 2 * 8 = 16 3 * 8 = 24 4 * 8 = 32 5 * 8 = 40 6 * 8 = 48 7 * 8 = 56 8 * 8 = 64
1 * 9 = 9 2 * 9 = 18 3 * 9 = 27 4 * 9 = 36 5 * 9 = 45 6 * 9 = 54 7 * 9 = 63 8 * 9 = 72 9 * 9 = 81
```