Kotlin-基础语法练习一

Example:

kotlin 复制代码
fun main(args: Array<String>) {
    var a= 10 + 20
    println(a)
}

Output:

kotlin 复制代码
30

Arithmetic Operators-算术运算符:

Operators Meaning Expression Translate to
+ Addition a + b a.plus(b)
- Subtraction a - b a.minus(b)
* Multiplication a * b a.times(b)
/ Division a / b a.div(b)
% Modulus a % b a.rem(b)

Example:

kotlin 复制代码
fun main(args: Array<String>)
{
    var a = 20 
    var b = 4 
    println("a + b = " + (a + b))
    println("a - b = " + (a - b))
    println("a * b = " + (a.times(b)))
    println("a / b = " + (a / b))
    println("a % b = " + (a.rem(b)))
}

Output:

kotlin 复制代码
a + b = 24
a - b = 16
a * b = 80
a / b = 5
a % b = 0

Relational Operators-关系运算符

Operators Meaning Expression Translate to
> greater than a > b a.compareTo(b) > 0
< less than a < b a.compareTo(b) < 0
>= greater than or equal to a >= b a.compareTo(b) >= 0
<= less than or equal to a <= b a.compareTo(b) <= 0
== is equal to a == b a?.equals(b) ?: (b === null)
!= not equal to a != b !(a?.equals(b) ?: (b === null)) > 0

Example:

kotlin 复制代码
fun main(args: Array<String>)
{
    var c = 30
    var d = 40
    println("c > d = "+(c>d))
    println("c < d = "+(c.compareTo(d) < 0))
    println("c >= d = "+(c>=d))
    println("c <= d = "+(c.compareTo(d) <= 0))
    println("c == d = "+(c==d))
    println("c != d = "+(!(c?.equals(d) ?: (d === null))))
}

Output:

kotlin 复制代码
c > d = false
c < d = true
c >= d = false
c <= d = true
c == d = false
c != d = true

Assignment Operators-赋值运算符

Operators Expression Translate to
= a = 5 a.equalto(5)
+= a = a + b a.plusAssign(b) > 0
-= a = a - b a.minusAssign(b) < 0
*= a = a * b a.timesAssign(b)>= 0
/= a = a / b a.divAssign(b) <= 0
%= a = a % b a.remAssign(b)

Example:

kotlin 复制代码
fun main(args : Array<String>){
 var a = 10
    var b = 5
    a+=b
    println(a)
    a-=b
    println(a)
    a*=b
    println(a)
    a/=b
    println(a)
    a%=b
    println(a)

}

Output:

kotlin 复制代码
15
10
50
10
0

Unary Operators-单目运算符

Operators Expression Translate to
++ ++a or a++ a.inc()
-- --a or a-- a.dec()

Example:

kotlin 复制代码
fun main(args : Array<String>){
    var e=10
    var flag = true
    println("First print then increment: "+ e++)
    println("First increment then print: "+ ++e)
    println("First print then decrement: "+ e--)
    println("First decrement then print: "+ --e)
}

Output:

kotlin 复制代码
First print then increment: 10
First increment then print: 12
First print then decrement: 12
First decrement then print: 10

Logical Operatorsz-逻辑运算符

Operators Meaning Expression
&& Return true if all expressions are true (a>b) && (a>c)
|| Return true if any of the expressions is true (a>b)
! Return the complement of the expression a.not()

Example:

kotlin 复制代码
fun main(args : Array<String>){
    var x = 100
    var y = 25
    var z = 10
    var result = false
    if(x > y && x > z)
     println(x)
    if(x < y || x > z)
     println(y)
    if( result.not())
     println("Logical operators")
}

Output:

kotlin 复制代码
100
25
Logical operators

Bitwise Operators-位运算符

Operators Meaning Expression
shl signed shift left a.shl(b)
shr signed shift right a.shr(b)
ushr unsigned shift right a.ushr()
and bitwise and a.and(b)
or bitwise or a.or()
xor bitwise xor a.xor()
inv bitwise inverse a.inv()

Example:

kotlin 复制代码
fun main(args: Array<String>)
{
    println("5 signed shift left by 1 bit: " + 5.shl(1))
    println("10 signed shift right by 2 bits: : " + 10.shr(2))
    println("12 unsigned shift right by 2 bits:  " + 12.ushr(2))
    println("36 bitwise and 22: " + 36.and(22))
    println("36 bitwise or 22: " + 36.or(22))
    println("36 bitwise xor 22: " + 36.xor(22))
    println("14 bitwise inverse is: " + 14.inv())
}

Output:

kotlin 复制代码
5 signed shift left by 1 bit: 10
10 signed shift right by 2 bits: : 2
12 unsigned shift right by 2 bits:  3
36 bitwise and 22: 4
36 bitwise or 22: 54
36 bitwise xor 22: 50
14 bitwise inverse is: -15

Kotlin Output-Kotlin 输出

print() function // prints text

println() function // prints text and then moves the cursor to a new line

Example:

kotlin 复制代码
fun main(args: Array<String>)
{
    print("Hello, Geeks! ")
    println("This is Kotlin tutorial.")
    print("By GFG!")
}

Output:

kotlin 复制代码
Hello, Geeks! This is Kotlin tutorial.
By GFG!

Print Literals and Variables-打印字面量和变量

Example:

kotlin 复制代码
fun sum(a: Int,b: Int) : Int{
    return a + b
}

fun main(args: Array<String>){

    var a = 10
    var b = 20
    var c = 30L
    var marks = 40.4

    println("Sum of {$a} and {$b} is : ${sum(a,b)}")
    println("Long value is: $c")
    println("marks")
    println("$marks")
}

Output:

kotlin 复制代码
Sum of {10} and {20} is : 30
Long value is: 30
marks
40.4 

Kotlin Input-Kotlin 输入

readline() method

Scanner class

Example:

kotlin 复制代码
fun main(args : Array<String>) {
    print("Enter text: ")
    var input = readLine()
    print("You entered: $input")
}

Output:

kotlin 复制代码
Enter text: Hello, Geeks! You are learning how to take input using readline()
You entered: Hello, Geeks! You are learning how to take input using readline()

使用Scanner类从用户获取输入

Example:

kotlin 复制代码
import java.util.Scanner

fun main(args: Array<String>) {
    
    // create an object for scanner class
    val number1 = Scanner(System.`in`)       
    print("Enter an integer: ")
    // nextInt() method is used to take 
    // next integer value and store in enteredNumber1 variable
    var enteredNumber1:Int = number1.nextInt()
    println("You entered: $enteredNumber1")

    val number2 = Scanner(System.`in`)
    print("Enter a float value: ")

    // nextFloat() method is used to take next
    // Float value and store in enteredNumber2 variable
    var enteredNumber2:Float = number2.nextFloat()
    println("You entered: $enteredNumber2")

    val booleanValue = Scanner(System.`in`)
    print("Enter a boolean: ")
    // nextBoolean() method is used to take 
    // next boolean value and store in enteredBoolean variable
    var enteredBoolean:Boolean = booleanValue.nextBoolean()
    println("You entered: $enteredBoolean")
}

Output:

kotlin 复制代码
Enter an integer: 123
You entered: 123
Enter a float value:  40.45
You entered: 40.45
Enter a boolean:  true
You entered: true

在不使用Scanner类的情况下从用户获取输入:

readline () ! !将输入作为字符串,并在后面加上(!!)以确保输入值不为空。
Example:

kotlin 复制代码
fun main(args: Array<String>) {

    print("Enter an Integer value: ")
    val string1 = readLine()!!  

    // .toInt() function converts the string into Integer
    var integerValue: Int = string1.toInt() 
    println("You entered: $integerValue")

    print("Enter a double value: ")
    val string2= readLine()!!

    // .toDouble() function converts the string into Double
    var doubleValue: Double = string2.toDouble() 
    println("You entered: $doubleValue")
}

Output:

kotlin 复制代码
Enter an Integer value: 123
You entered: 123
Enter a double value:  22.22222
You entered: 22.22222

Kotlin Type Conversion- Kotlin类型转换

类型转换(也称为类型强制转换)是指将一种数据类型变量的实体更改为另一种数据类型。正如我们所知,Java支持从较小数据类型到较大数据类型的隐式类型转换。整数值可以分配给long数据类型。
但是,Kotlin不支持隐式类型转换。整数值不能分配给长数据类型。
Example:

kotlin 复制代码
public class TypecastingExample {  
   public static void main(String args[]) {  
      byte p = 12;  
      System.out.println("byte value : "+p);
      
      // Implicit Typecasting 
      // integer value can be assigned
      // to long data type
      long q = p;
    }
 }

Output:

kotlin 复制代码
var myNumber = 100
var myLongNumber: Long = myNumber       // Compiler error
// Initializer type mismatch: expected 'Long', actual 'Int'.
kotlin 复制代码
var myNumber = 100
var myLongNumber: Long = myNumber.toLong()     // compiles successfully

下面的辅助函数可用于将一种数据类型转换为另一种数据类型:

kotlin 复制代码
toByte() 
toShort() 
toInt() 
toLong() 
toFloat() 
toDouble() 
toChar() 

Example:

java 复制代码
fun main(args: Array<String>)
{
  
    println("259 to byte: " + (259.toByte()))
    println("50000 to short: " + (50000.toShort()))
    println("21474847499 to Int: " + (21474847499.toInt()))
    println("10L to Int: " + (10L.toInt()))
    println("22.54 to Int: " + (22.54.toInt()))
    println("22 to float: " + (22.toFloat()))
    println("65 to char: " + (65.toChar()))
    // Char to Number is deprecated in kotlin
    println("A to Int: " + ('A'.toInt()))
}

Output:

kotlin 复制代码
259 to byte: 3
50000 to short: -15536
21474847499 to Int: 11019
10L to Int: 10
22.54 to Int: 22
22 to float: 22.0
65 to char: A
A to Int: 65
相关推荐
恋猫de小郭7 小时前
2026 Flutter VS React Native ,同时在 AI 时代 VS Native 开发,你没见过的版本
android·前端·flutter
冬奇Lab8 小时前
PowerManagerService(上):电源状态与WakeLock管理
android·源码阅读
BoomHe13 小时前
Now in Android 架构模式全面分析
android·android jetpack
二流小码农21 小时前
鸿蒙开发:上传一张参考图片便可实现页面功能
android·ios·harmonyos
鹏程十八少21 小时前
4.Android 30分钟手写一个简单版shadow, 从零理解shadow插件化零反射插件化原理
android·前端·面试
Kapaseker21 小时前
一杯美式搞定 Kotlin 空安全
android·kotlin
三少爷的鞋1 天前
Android 协程时代,Handler 应该退休了吗?
android
火柴就是我1 天前
让我们实现一个更好看的内部阴影按钮
android·flutter
FunnySaltyFish2 天前
什么?Compose 把 GapBuffer 换成了 LinkBuffer?
算法·kotlin·android jetpack
砖厂小工2 天前
用 GLM + OpenClaw 打造你的 AI PR Review Agent — 让龙虾帮你审代码
android·github