Skip to content

Commit 533d470

Browse files
committed
Added code for funny number guessing game on Main.kt and new lessons 😄
Added code to the Main.kt file that implements a cool number guessing game. The code allows the user to input the range of numbers, generates a random number within that range, and prompts the user to guess the generated number. The user is given a limited number of attempts to guess the number correctly. The code also calculates the user's score based on the range difficulty and the number of remaining attempts. Additionally, included 8 new lessons and associated images. 🎉
1 parent edb9948 commit 533d470

File tree

11 files changed

+790
-0
lines changed

11 files changed

+790
-0
lines changed
Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
# Reading data with readln
2+
3+
In this topic, you will learn how to read information from user input and interact with it. You'll explore how to manage variables using the `readln()` function and work with different data types.
4+
5+
## Standard input
6+
7+
Standard input is a stream of data that goes into a program. It is supported by the operating system and, by default, obtains data from the keyboard. However, it is also possible to get input from a file.
8+
9+
Although not all programs require standard input, you'll frequently encounter situations where it's needed. The typical approach to solving programming problems involves:
10+
11+
1. Reading data from standard input.
12+
2. Processing the data to obtain a result.
13+
3. Outputting the result to standard output.
14+
15+
Before writing programs that perform useful tasks, it's important to understand how to read data from standard input.
16+
17+
## Using readln
18+
19+
In Kotlin, you can use the `readln()` function to read data from standard input. This function reads the entire line as a string:
20+
21+
```kotlin
22+
val line = readln()
23+
```
24+
The variable line has the type String because readln() returns a value of that type.
25+
26+
In older versions of Kotlin, you may need to use readLine()!! instead of readln(). These functions do the same thing, but readln() is shorter and preferred. If you're using Kotlin 1.6 or higher, use readln().
27+
28+
```kotlin
29+
val line = readLine()!! // before Kotlin 1.6
30+
```
31+
Note the exclamation marks. This construction ensures non-empty input to the compiler. We'll discuss it in more detail later.
32+
33+
Here's a simple program that reads a line from standard input and outputs it to standard output:
34+
35+
```kotlin
36+
fun main() {
37+
val line = readln()
38+
println(line)
39+
}
40+
```
41+
For example, if the input is "Hello, Kotlin", the output will be the same:
42+
43+
```yaml
44+
Hello, Kotlin
45+
```
46+
By default, you need to press Enter to see the input information.
47+
48+
Now, let's explore how to read different types of data using **readln()**.
49+
50+
## toInt() and toLong()
51+
Sometimes you need to read numeric data from the user, such as their age or graduation year. To work with numeric values, you can use the **toInt()** function. To convert the input to an integer, use the **toInt()** function with dot syntax:
52+
53+
```kotlin
54+
println("Enter any number: ")
55+
val number = readln().toInt()
56+
print("You entered the number: ")
57+
print(number)
58+
```
59+
For example, if the input is "56", the output will be:
60+
61+
```csharp
62+
Enter any number:
63+
56
64+
You entered the number: 56
65+
```
66+
If you need to process larger numbers, like the cost of a luxury yacht, you can use the **toLong()** function:
67+
68+
```kotlin
69+
println("How much is your yacht worth?")
70+
val cost = readln().toLong()
71+
print("You entered: ")
72+
print(cost)
73+
```
74+
For example, if the input is "10000000000", the output will be:
75+
76+
```csharp
77+
How much is your yacht worth?
78+
10000000000
79+
You entered: 10000000000
80+
```
81+
## toDouble() and toBoolean()
82+
What if you need more precise values? For example, if you need to know the exact price of a liter of gasoline. In this case, you can't use **toInt()** or **toLong()** because the value might not be a whole number. Instead, you can use the **toDouble()** function:
83+
84+
```kotlin
85+
println("Enter any double type number:")
86+
val number = readln().toDouble()
87+
println("You entered the number: ")
88+
print(number)
89+
```
90+
For example, if the input is "0.5673421", the output will be:
91+
92+
```arduino
93+
Enter any double type number:
94+
0.5673421
95+
You entered the number: 0.5673421
96+
```
97+
The same logic applies to Boolean values. You can use the **toBoolean()** function:
98+
99+
```kotlin
100+
println("The earth is flat. Type true or false:")
101+
val answer = readln().toBoolean()
102+
print("The earth is flat: ")
103+
print(answer)
104+
```
105+
For example, if the input is "false", the output will be:
106+
107+
```csharp
108+
The earth is flat. Type true or false:
109+
false
110+
The earth is flat: false
111+
```
112+
## Multiple inputs
113+
Is it possible to receive and process multiple inputs? Yes, it is. You can declare multiple variables and assign them the value of the **readln()** function. If you want to enter several values with different data types, you need to press Enter to separate them.
114+
115+
Here's an example that demonstrates multiple inputs and outputs:
116+
117+
```kotlin
118+
val a = readln()
119+
val b = readln().toInt()
120+
val c = readln()
121+
print(a)
122+
print(" ")
123+
print(b)
124+
print(" ")
125+
print(c)
126+
```
127+
For example, if the inputs are "You earned", "100", and "points!", the output will be:
128+
129+
```yaml
130+
You earned 100 points!
131+
```
132+
As you can see, handling multiple values of different data types is straightforward. You just need to declare multiple variables, assign them the desired **readln()** function, and display them correctly in the console.
133+
134+
## Reading multiple values in one line
135+
If you need to read two values on the same line, you can use the following construction:
136+
137+
```kotlin
138+
val (a, b) = readln().split(" ")
139+
println(a)
140+
println(b)
141+
```
142+
For example, if the input is "Hello, Kotlin", the output will be:
143+
144+
```yaml
145+
Hello,
146+
Kotlin
147+
```
148+
This construction splits the input string at spaces and stores the words in the variables **a** and **b**. We'll discuss this in more detail later.
149+
150+
Similarly, you can read up to four values per line:
151+
152+
```kotlin
153+
val (a, b, c, d) = readln().split(" ")
154+
println(a)
155+
println(b)
156+
println(c)
157+
println(d)
158+
```
159+
For example, if the input is "Have a nice Kotlin", the output will be:
160+
161+
```yaml
162+
Have
163+
a
164+
nice
165+
Kotlin
166+
```
167+
## Conclusion
168+
As you can see, reading input is straightforward in Kotlin. All you need to do is declare a variable with the value of the **readln()** function. The **readln()** function automatically converts the input to a **String** type. Your program can handle string, number, and boolean input by using type conversion with functions such as **toInt()**, **toLong()**, **toDouble()**, and **toBoolean()**. You can also handle multiple values of the same or different types.
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
# String Basics
2+
In this lesson, we will explore the basics of working with strings in Kotlin. Strings are a fundamental data type in Kotlin and are used to represent sequences of characters. Understanding string operations and manipulations is essential for various programming tasks. Let's dive into the important concepts related to strings.
3+
4+
## The Length of a String
5+
To determine the length of a string, you can use the **.length** property. It returns the number of characters in the string. Here's an example:
6+
7+
```kotlin
8+
val language = "Kotlin"
9+
println(language.length) // Output: 6
10+
11+
val empty = ""
12+
println(empty.length) // Output: 0
13+
```
14+
In the above example, **language.length** returns **6** since the string "**Kotlin**" consists of six characters. Similarly, **empty.length** returns **0** as the empty string has no characters.
15+
16+
## Concatenating Strings
17+
Concatenation is the process of combining two or more strings into a single string. In Kotlin, you can use the **+** operator to concatenate strings. Here's an example:
18+
19+
```kotlin
20+
val str1 = "ab"
21+
val str2 = "cde"
22+
val result = str1 + str2 // Output: "abcde"
23+
```
24+
In the above example, the strings "**ab**" and "**cde**" are concatenated using the **+** operator, resulting in the string "**abcde**".
25+
26+
You can also concatenate multiple strings in the same expression:
27+
28+
```kotlin
29+
val firstName = "John"
30+
val lastName = "Smith"
31+
val fullName = firstName + " " + lastName
32+
```
33+
In the above example, the strings "**John**", **" "**, and "**Smith**" are concatenated to form the full name "**John Smith**".
34+
35+
## Appending Values to Strings
36+
You can append values of different types to a string using the **+** operator. The values are automatically converted to strings and then concatenated to the target string. Here's an example:
37+
38+
```kotlin
39+
val stringPlusBoolean = "abc" + 10 + true
40+
println(stringPlusBoolean) // Output: abc10true
41+
42+
val code = "123" + 456 + "789"
43+
println(code) // Output: 123456789
44+
```
45+
In the above example, the integer **10** and the boolean value true are appended to the string "**abc**". Similarly, the integer **456** is appended between the strings "**123**" and "**789**".
46+
47+
It's important to note that the concatenation operation is not commutative. The order of concatenation matters. For example:
48+
49+
```kotlin
50+
val one = "1"
51+
val two = "2"
52+
val twelve = one + two
53+
println(twelve) // Output: 12
54+
```
55+
In the above example, **one** + **two** concatenates the strings in the order they appear, resulting in the string "**12**".
56+
57+
## Repeating the String
58+
![To do](https://github.com/ArtemZarubin/kotlin-lessons/blob/master/src/main/images/todo.png)
59+
60+
If you need to repeat a string multiple times, you can use the **repeat()** function. It takes an integer argument specifying the number of repetitions. Here's an example:
61+
62+
```kotlin
63+
print("Hello".repeat(4)) // Output: HelloHelloHelloHello
64+
```
65+
In the above example, the string "**Hello**" is repeated four times using the **repeat()** function, resulting in the output "**HelloHelloHelloHello**".
66+
67+
## Raw String
68+
In some cases, you may need to include special characters like tabs or quotes in a string. To make it easier to write such strings, Kotlin provides raw strings. Raw strings can contain newlines and any other characters without the need for escape sequences. To define a raw string, enclose the text in triple quotes (**"""**). Here's an example:
69+
70+
```kotlin
71+
val largeString = """
72+
This is the house that Jack built.
73+
74+
This is the malt that lay in the house that Jack built.
75+
76+
This is the rat that ate the malt
77+
That lay in the house that Jack built.
78+
79+
This is the cat
80+
That killed the rat that ate the malt
81+
That lay in the house that Jack built.
82+
""".trimIndent()
83+
print(largeString)
84+
```
85+
In the above example, the raw string contains multiple lines and preserves the indentation. The **trimIndent()** function is used to remove the common minimal indent and trim the leading and trailing empty lines.
86+
87+
## Conclusion
88+
In this lesson, we covered the basic operations and concepts related to strings in Kotlin. You learned about finding the length of a string, concatenating strings, appending values, repeating strings, and using raw strings. These foundational string operations are essential for manipulating and working with text in your Kotlin programs. Keep practicing and exploring the vast possibilities that strings offer in your programming journey. Good luck!
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# String Templates
2+
In this lesson, we will explore string templates in Kotlin. String templates provide a convenient way to include variable values and expressions within strings. Let's dive into their purpose and usage.
3+
4+
## Introduction to String Templates
5+
String templates allow us to insert variable values into a string and build dynamic messages or texts. Instead of manually concatenating strings and variables, we can use string templates to achieve the same result in a more readable and concise manner.
6+
7+
## Basic Variable Interpolation
8+
To include the value of a variable within a string, we can use the dollar sign **$** followed by the variable name. The variable's value will be automatically inserted into the string. Here's an example:
9+
10+
```kotlin
11+
val city = "Paris"
12+
val temp = "24"
13+
14+
println("Now, the temperature in $city is $temp degrees Celsius.")
15+
```
16+
In the above example, the values of the variables **city** and **temp** are interpolated within the string using string templates. The resulting string is: "Now, the temperature in Paris is 24 degrees Celsius."
17+
18+
Using string templates makes the code more readable and eliminates the need for explicit string concatenation.
19+
20+
## Expressions in String Templates
21+
String templates also allow us to include the result of arbitrary expressions within a string. To do this, enclose the expression within curly braces **{}** after the dollar sign **$**. Here's an example:
22+
23+
```kotlin
24+
val language = "Kotlin"
25+
println("$language has ${language.length} letters in the name")
26+
```
27+
In the above example, we use the expression **${language.length}** within the string template to retrieve the length of the **language** variable and include it in the string. The resulting output is: "Kotlin has 6 letters in the name."
28+
29+
By using curly braces, we can evaluate any expression and include its result in the string template.
30+
31+
## Idioms: String Interpolation
32+
Idioms are established patterns or practices that enhance the clarity and readability of code. String interpolation is an idiom in Kotlin that encourages the use of string templates for variable interpolation. It is considered a best practice in Kotlin coding style. Here's an example:
33+
34+
```kotlin
35+
val language = "Kotlin"
36+
println("Have a nice $language!") // Good practice
37+
println("Have a nice " + language + "!") // Less preferred
38+
```
39+
In the above example, the first line uses string interpolation with the **variable** language directly embedded within the string using **$language**. This is the preferred and idiomatic way to achieve string interpolation in Kotlin. The second line demonstrates the less preferred method of string concatenation using the **+** operator.
40+
41+
## Conclusion
42+
In this lesson, we covered string templates in Kotlin. We learned how to interpolate variable values within strings using the dollar sign **$** and include expressions within curly braces **{}** in string templates. We also discussed the idiom of string interpolation and its benefits for writing clear and readable code.
43+
44+
Remember the following key points:
45+
46+
1. Use string templates to insert variable values into a string: "**This string has $value**".
47+
2. Use curly braces for expressions in string templates: "The length is **${str.length}**".
48+
49+
By utilizing string templates effectively, you can create dynamic and expressive strings in your Kotlin code.
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# Boolean and Logical Operations
2+
In this lesson, we will explore boolean values and logical operations in Kotlin. Booleans are fundamental data types that represent two opposite states: true and false. We will learn how to work with boolean variables and utilize logical operators to construct logical statements.
3+
4+
## Boolean Variables
5+
Boolean variables in Kotlin can hold one of two values: true or false. Here's an example:
6+
7+
![Foreign friend](https://github.com/ArtemZarubin/kotlin-lessons/blob/master/src/main/images/true-and-false.svg)
8+
9+
```kotlin
10+
val t = true // t is true
11+
val f = false // f is false
12+
13+
println(t) // true
14+
println(f) // false
15+
```
16+
Note that you cannot assign an integer value to a boolean variable. In Kotlin, 0 is not equivalent to false.
17+
18+
## Reading Boolean Values
19+
In Kotlin 1.4 and later versions, you can read a boolean value from user input using **readLine().toBoolean()**. For Kotlin 1.6 and newer, you can use **readln().toBoolean()**.
20+
21+
```kotlin
22+
val b: Boolean = readLine().toBoolean()
23+
24+
// Example input:
25+
// true
26+
// Output:
27+
// true
28+
```
29+
The **toBoolean()** function converts the user input to a boolean value. If the input is "true" (case-insensitive), it returns true. Otherwise, it returns false.
30+
31+
## Logical Operators
32+
Kotlin provides four logical operators for working with boolean values:
33+
34+
**NOT**: Reverses the boolean value. Denoted by the **!** operator.
35+
**AND**: Returns true if both operands are true. Denoted by the **&&** operator.
36+
**OR**: Returns true if at least one operand is true. Denoted by the **||** operator.
37+
**XOR** (Exclusive OR): Returns true if the operands have different values. Denoted by the **xor** operator.
38+
Here are examples illustrating the usage of logical operators:
39+
40+
```kotlin
41+
val f = false // f is false
42+
val t = !f // t is true (NOT operator)
43+
44+
val b1 = false && false // false (AND operator)
45+
val b2 = false || true // true (OR operator)
46+
val b3 = true xor false // true (XOR operator)
47+
```
48+
The logical operators allow you to combine boolean values and create complex logical expressions.
49+
50+
## Logical Operator Precedence
51+
Logical operators in Kotlin have a specific order of precedence. Here's the precedence from highest to lowest:
52+
53+
- **!** (NOT)
54+
- **xor** (XOR)
55+
- **&&** (AND)
56+
- **|** (OR)
57+
Parentheses can be used to change the order of execution. For example:
58+
59+
```kotlin
60+
val bool = true && !false // true (NOT is evaluated first)
61+
```
62+
By understanding the operator precedence, you can control the grouping of variables in logical expressions.
63+
64+
## Conclusion
65+
In this lesson, we explored boolean values and logical operations in Kotlin. We learned about boolean variables, logical operators (NOT, XOR, AND, OR), and the precedence of logical operations. Understanding these concepts is essential for mastering Kotlin programming. Logical operations are powerful tools for making decisions and controlling program flow based on boolean conditions. Practice and experimentation will further solidify your understanding. Now, let's move on to solving some tasks to reinforce your knowledge.

0 commit comments

Comments
 (0)