Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Function Call, Arithmetic Operations, User Input and more in Kotlin
/* PROGRAM BY 'JAMES COLLINS' This program demonstrates the following: i - Variable declaration in Kotlin ii - User-input in Kotlin using Java's Scanner class. iii - Object creation. iv - Output. v - String formatting. vi - Class creation. vii - Method declaration. viii - Passing values to functions/methods. ix - Conditional statements x - Recursion. xi - Comments (Single-line and Mulitline) Thanks for reading. */ import java.util.Scanner class Arithmetic { public fun add(num1: Int, num2: Int): Int { return num1 + num2 // adding the 2 numbers } public fun diff(num1: Int, num2: Int): Int { return abs(num1 - num2) // substracting the 2 numbers and getting the absolute value. } public fun multi(num1: Int, num2: Int): Long { return (num1 * 1L) * num2 // Multiplying 2 numbers. } public fun div(num1: Int, num2: Int): Float { return (num1 / (num2 * 1.0f)) // Converting one of the numbers to a float so that we can do floating-point calculations. } public fun abs(num:Int): Int { // This part uses the 'ternary' operator of Kotlin, which is more like an 'if' statement than a simple ternary operator like in Java. // In Java you can do this statement like this:- (num < 0) ? -num : num; // It easier to type, but I gotta admit, Kotlin's ternary operator is easier to understand from a beginner's perspective. return if(num < 0) -num else num } public fun factorial(num:Int): Long { if(num == 0) return 1 else if(num == 1) return 1 else return num * factorial(num - 1) // This is where the recursion part comes in. } } fun main() { val scanner = Scanner(System.`in`) // It's good to use 'val' keyword while declaring an Object (Variables declared as 'val' are constants.) val practice = Arithmetic() var num_input: Int = scanner.nextInt() // Variables declared as 'var' are mutable. (value can be changed during runtime.) var num_input1: Int = scanner.nextInt() println("Sum is: ${practice.add(input, input1)}") // Here you can see the way to do string formatting in Kotlin. println("Difference is: ${practice.diff(input, input1)}") println("Product is: ${practice.multi(input, input1)}") println("Quotient is: ${practice.div(input, input1)}") println("Facotrial is: ${practice.factorial(5)}") } // PROGRAM BY 'JAMES COLLINS'
run
|
edit
|
history
|
help
0
Aula 1 - Orientacao a Objetos - Mao na Massa
My script1
Result finder
Fibonacci in Kotlin
Haha
?. in Kotlin
iya
degerliilkornek
KotlineMerg
KotlinCopy