scala的九九乘法表的while
时间: 2024-06-15 09:07:56 浏览: 16
Scala是一种运行在Java虚拟机上的编程语言,它结合了面向对象编程和函数式编程的特性。下面是使用while循环打印九九乘法表的Scala代码:
```scala
var i = 1
while (i <= 9) {
var j = 1
while (j <= i) {
print(s"$j * $i = ${i * j}\t")
j += 1
}
println()
i += 1
}
```
这段代码使用了两个嵌套的while循环来打印九九乘法表。外层循环控制行数,内层循环控制每行的列数。在内层循环中,使用字符串插值将乘法表的每个元素打印出来,并使用制表符`\t`进行对齐。最后,通过`println()`换行。
相关问题
scala九九乘法表代码
Scala是一种高级编程语言,它融合了面向对象编程和函数式编程的特性,可以运行在Java虚拟机上。下面是一个Scala实现的九九乘法表代码示例:
```scala
object MultiplicationTable {
def main(args: Array[String]): Unit = {
for(i <- 1 to 9; j <- 1 to i) {
print(j + " × " + i + " = " + (i*j) + "\t")
if(i == j) println()
}
}
}
```
代码解释:
- `object MultiplicationTable`:定义了一个名为MultiplicationTable的单例对象
- `def main(args: Array[String]): Unit`:定义了一个名为main的方法,参数为字符串数组,返回值类型为Unit(相当于Java中的void)
- `for(i <- 1 to 9; j <- 1 to i)`:使用for循环嵌套,i从1到9,j从1到i
- `print(j + " × " + i + " = " + (i*j) + "\t")`:打印出乘法表中的每一项
- `if(i == j) println()`:当i等于j时,换行打印下一行的乘法表
相关问题:
1. Scala是什么?有哪些特点?
2. 什么是Scala的单例对象?
3. 如何在Scala中使用for循环?
scala九九乘法表
Sure! Here's an example of how you can generate a 9x9 multiplication table using Scala:
```scala
object MultiplicationTable {
def main(args: Array[String]): Unit = {
for (i <- 1 to 9) {
for (j <- 1 to 9) {
val result = i * j
print(f"$i * $j = $result\t")
}
println()
}
}
}
```
When you run this program, it will print the multiplication table from 1x1 to 9x9. Each multiplication expression will be formatted as "i * j = result". The "\t" is used to add a tab space between each expression for better readability.
Feel free to give it a try and let me know if you have any further questions!