03. 函数
2022年5月7日
03. 函数
1. 可以传递数组对象并修改
fun changeArray( game:Array<String>){
game[1]="翻跟头"
}
fun main(args: Array<String>) {
val games= arrayOf("吃饭","睡觉","打豆豆")
changeArray(games)
for (game in games) {
print(game)
}
}
输出:
吃饭翻跟头打豆豆
2. 改变基本数据类型是否会影响引用
fun changeArray( game:Array<String>){
game[1]="翻跟头"
}
fun main(args: Array<String>) {
var eat="吃饭"
val games= arrayOf(eat,"睡觉","打豆豆")
changeArray(games)
eat="吃水果"
for (game in games) {
print(game)
}
}
输出:
吃饭翻跟头打豆豆
结论
基本类型向对象中传递时,是拷贝内存中的数据,持有副本,而不是持有原基本类型的引用。
3. 函数的参数为基本类型时
默认val 只读状态,不可修改,编译器报错
fun changStr(str:String){
str="test" //编译器报错
}
4. for循环的几种用法
4.1 遍历元素和下标
fun main(args: Array<String>) {
val games = arrayOf("石头", "剪刀", "布")
for (game in games) {
print(game)
}
println()
for(index in 0..games.size){
print(index)
}
println()
for(item in games.iterator()){
print(item)
}
println()
for((index,item) in games.withIndex()){
print("$index: $item ")
}
}
4.2 不包含右值的循环
和使用循环一个意思
fun main(args: Array<String>) {
val games = arrayOf("石头", "剪刀", "布")
for(index in 0 until games.size){
println(index)
}
}
4.3 逆序循环
fun main(args: Array<String>) {
val games = arrayOf("石头", "剪刀", "布")
for(index in games.size-1 downTo 0){
println(index)
}
}
输出
2 1 0
4.4 step
跳过范围内的
fun main(args: Array<String>) {
val games = arrayOf("石头", "剪刀", "布")
for(index in games.indices step 2){
println(index)
}
}
输出
0
2
石头剪刀布游戏
fun main(args: Array<String>) {
val games = arrayOf("石头", "剪刀", "布")
val me = Player()
val robot = Player(name = "机器人")
println("请输入玩家名称:")
me.name = readLine() ?: "player"
Thread{
while (true) {
println("-----------------------\n\n")
//获取我出的拳
// me.value = getMeValue(games) //手动出拳
me.value = getRobotValue(games) //机器人自己出拳
//获取机器人出拳
robot.value = getRobotValue(games)
//判决谁赢了
judgment(me, robot)
// Thread.sleep(1000) // 一秒出一次
}
}.start()
}
fun judgment(player: Player, player1: Player) {
println("${player.name}出了${player.value}")
println("${player1.name}出了${player1.value}")
if (player.value == player1.value) {
println("平局")
} else if (player.value == "石头" && player1.value == "剪刀" || player.value == "剪刀" && player1.value == "布" || player.value == "布" && player1.value == "石头") {
player.victories += 1
} else {
player1.victories += 1
}
println("${player.name} 胜${player.victories}场")
println("${player1.name} 胜${player1.victories}场")
}
data class Player(var name: String = "默认玩家", var value: String = "石头", var victories: Int = 0)
fun getMeValue(games: Array<String>): String {
var myPrint: Int
while (true) {
println("请选择你要出的拳:")
for ((index, item) in games.withIndex()) {
println("${index + 1}. $item")
}
myPrint =
try {
readLine()!!.toInt()
} catch (e: NumberFormatException) {
continue
}
if (myPrint > 0 && myPrint < games.size + 1) {
return games[myPrint - 1]
} else {
continue
}
}
}
fun getRobotValue(games: Array<String>): String {
return games[(Math.random() * games.size).toInt()]
}