A very basic question, What is the right approach to concatenate String to an Int?
I'm new in Kotlin and want to print an Integer value preceding with String and getting the following error message.
for (i in 15 downTo 10){
print(i + " "); //error: None of the following function can be called with the argument supplied:
print(i); //It's Working but I need some space after the integer value.
}
Expected Outcome
15 14 13 12 11 10
You've got several options:
1. String templates. I think it is the best one. It works absolutely like 2-st solution, but looks better and allow to add some needed characters.
print("$i")
and if you want to add something
print("$i ")
print("$i - is good")
to add some expression place it in brackets
print("${i + 1} - is better")
2. toString method which can be used for any object in kotlin.
print(i.toString())
3. Java-like solution with concatenating
print("" + i)
$ dollar – Dollar symbol is used in String templates that we’ll be seeing next
for (i in 15 downTo 10){
print("$i ")
}
Output : 15 14 13 12 11 10
You can use kotlin string template for that:
for (i in 15 downTo 10){
print("$i ");
}
https://kotlinlang.org/docs/reference/basic-types.html#string-templates
The Int::toString method does what you're looking for. Instead of explicit loops, consider functional approaches like map:
(15 downTo 10).map(Int::toString).joinToString { " " }
Note that the map part is even redundant since joinToString can handle the conversion internally.
The error you get is because the + you're using is the integer one (it is decided by the left operand). The integer + expects 2 integers. In order to actually use the + of String for concatenation, you would need the string on the left, like "" + i + " ".
That being said, it is more idiomatic in Kotlin to print formatted strings using string templates: "$i "
However, if all you want is to print integers with spaces in between, you can use the stdlib function joinToString():
val output = (15 downTo 10).joinToString(" ")
print(output) // or println() if you want to start a new line after your integers
Just cast to String:
for (i in 15 downTo 10){
print(i.toString() + " ");
}
You should use the $ . You can also use the + but it could get confusing in your case because the + has is also an operator which invokes the plus() method which is used to sum Integers.
for (i in 15 downTo 10){
print("$i ");
}
Related
This question already has an answer here:
Drop un-needed decimal ".0"
(1 answer)
Closed 2 years ago.
fun equalsClick(view: View) {
val sec0perandText: String = resultTextView.text.toString()
var sec0perand: Double = 0.0.roundToInt()
if (!TextUtils.isEmpty(sec0perandText)) {
sec0perand = sec0perandText.toDouble()
}
when (operation) {
"+" -> resultTextView.text = (operand + sec0perand).toString()
"-" -> resultTextView.text = (operand - sec0perand).toString()
"*" -> resultTextView.text = (operand * sec0perand).toString()
"/" -> resultTextView.text = (operand / sec0perand).toString()
}
}
Getting output in double is not an option because it gives Integers .0 in the end. I tried adding .roundToInt() which didn't work, when compiled it gives following error: Type mismatch: inferred type is Int but Double was expected.
If I have understood correctly, you wanna get rid of the decimal zeros at the end of a double value (trailing zeros). If so, here is a clean solution.
Do all your calculations with double values and when you wanna print the result, do it this way:
resultTextView.text = String.format("%.0f", operand + sec0perand)
this will get rid of the decimal digits if they are zeros or other decimal values (it does not round your number just formats it)
I tried adding .roundToInt() which didn't work, when compiled it gives following error: Type mismatch: inferred type is Int but Double was expected.
You are just doing it in the wrong place, use
resultTextView.text = (operand + sec0perand).roundToInt().toString()
and so on.
I'm trying to find the simplest way to convert a digit (0..9) into the respective character '0'..'9' in Kotlin.
My initial attempt was to write the following code:
fun convertToCharacter() {
val number = 0
val character = number.toChar()
println(character)
}
Of course, after running, I quickly saw that this produces \u0000, and not '0' like I expected. Then, remembering from how to do this in Java, I modified the code to add '0', but then this would not compile.
fun convertToCharacter() {
val number = 0
val character = number.toChar() + '0'
println(character)
}
What is the appropriate way to convert a number into its respective character counterpart in Kotlin? Ideally, I'm trying to avoid pulling up the ASCII table to accomplish this (I know I can add 48 to the number since 48 -> '0' in ASCII).
val character = '0' + number
is the shortest way, given that the number is in range 0..9
Kotlin stdlib provides this function since 1.5.0.
fun Int.digitToChar(): Char
Returns the Char that represents this decimal digit. Throws an exception if this value is not in the range 0..9.
If this value is in 0..9, the decimal digit Char with code '0'.code + this is returned.
Example
println(5.digitToChar()) // 5
println(3.digitToChar(radix = 8)) // 3
println(10.digitToChar(radix = 16)) // A
println(20.digitToChar(radix = 36)) // K
Like you said, probably the easiest way to convert an Int to the Char representation of that same digit is to add 48 and call toChar():
val number = 3
val character = (number + 48).toChar()
println(character) // prints 3
If you don't want to have the magic 48 number in your program, you could first parse the number to a String and then use toCharArray()[0] to get the Char representation:
val number = 3
val character = number.toString().toCharArray()[0]
println(character) // prints 3
Edit: in the spirit of the attempt in your question, you can do math with '0'.toInt() and get the result you were expecting:
val number = 7
val character = (number + '0'.toInt()).toChar()
println(number) // prints 7
How about 0.toString() instead of 0.toChar() ? If you are specifically after single digits, then 0.toString()[0] will give you a Char type
You can use an extension like this:
fun Int.toReadableChar(): Char {
return ('0'.toInt() + this).toChar()
}
You can apply this to any other class you want :)
Example:
println(7.toReadableChar())
>> 7
Sorry this seems very basic but I'm missing something
I have a method signature override
fun doSomeWork (range: IntProgression, j: Int): List<Cell>{
I want to iterate the range whatever it is (could be up or down say 1 to 4 or 4 down to 1). The range itself seems to work, so on my 4 down to 1 example
println (range.first.toString() + " to " + range.last.toString() + ", step = " + range.step)
prints "4 to 1, step = 1"
but I can't seem to iterate the range ? I've tried a few things
for (i in range) {
println ("range: $i)"
}
and then
for (i in range.first until range.last step range.step){
println ("Loop de loop $i")
}
(although writing this question I noticed it is step 1 not -1 which may be the issue here ? but as I want to be able to pass in a range of either direction I haven't checked)
and then
range.forEach { println ("range foreach") }
none of them print anything, but they don't throw an error so any code after that runs through properly.
Can anyone point out why I'm failing to do this entry level task ?!
So you want an IntProgression from 4 to 1 with step -1, i.e. IntProgression.fromClosedRange(4, 1, -1) or better yet: 4.downTo(1). While you wrote your question you already realised the step... but the starting point isn't 1 then, but rather 4 ;-) With the downTo such problems will not arise, as the function takes care of the direction and it's also more readable then.
Note also that you can simply use reversed to reverse a progression:
range.reversed()
and either use it in a for-loop or with .forEach, etc.
So:
val range = IntProgression.fromClosedRange(1, 4, 1)
range.forEach(::print) // prints: 1234
range.reversed().forEach(::print) // prints: 4321
The forEach method can be used to iterate through the IntProgression. The it can be used to get the value or index.
fun doSomeWork (range: IntProgression) {
range.forEach {
println(it)
}
}
Invoking the above method:-
ClassName().doSomeWork(IntProgression.fromClosedRange(1,10, 1))
val range= IntProgression.fromClosedRange(1, 4, 1)
for (i in range)
println(i) // out put 1234
for (i in range.reversed())
println(i)//out put 4321
use
IntProgression.fromClosedRange(start, end, step)
for reverse range
IntProgression.reversed()
more details refer Ranges
I wanted to sum the digits of Long variable and add it to the variable it self, I came with the next working code:
private fun Long.sumDigits(): Long {
var n = this
this.toString().forEach { n += it.toString().toLong() }
return n
}
Usage: assert(48.toLong() == 42.toLong().sumDigits())
I had to use it.toString() in order to get it work, so I came with the next test and I don't get it's results:
#Test
fun toLongEquality() {
println("'4' as Long = " + '4'.toLong())
println("\"4\" as Long = " + "4".toLong())
println("\"42\" as Long = " + "42".toLong())
assert('4'.toString().toLong() == 4.toLong())
}
Output:
'4' as Long = 52
"4" as Long = 4
"42" as Long = 42
Is it a good practice to use char.toString().toLong() or there is a better way to convert char to Long?
Does "4" represented by chars? Why it is not equal to it char representation?
From the documentation:
class Char : Comparable (source) Represents a 16-bit Unicode
character. On the JVM, non-nullable values of this type are
represented as values of the primitive type char.
fun toLong(): Long
Returns the value of this character as a Long.
When you use '4' as Long you actually get the Unicode (ASCII) code of the char '4'
As mTak says, Char represents a Unicode value. If you are using Kotlin on the JVM, you can define your function as follows:
private fun Long.sumDigits() = this.toString().map(Character::getNumericValue).sum().toLong()
There's no reason to return Long rather than Int, but I've kept it the same as in your question.
Non-JVM versions of Kotlin don't have the Character class; use map {it - '0'} instead.
How can I make it in kotlin using for loop?
for (double i = 0; i < 10.0; i += 0.25) {
System.out.println("value is:" + i);
}
You should use the Intellij plugin for converting Java code for Kotlin. It's pretty neat (unless you have complex code using lambdas) This is what it converts to for your given question:
var i = 0.0
while (i < 10.0) {
println("value is:" + i)
i += 0.25
}
Here is the kotlin code equivalent to for loop.
var i = 0.0
while (i < 10.0)
{
println("value is:" + i)
i += 1.0
}
Kotlin for loop only support iterate the arrays.Please refer https://kotlinlang.org/docs/reference/control-flow.html
It's achievable in different way
var length:Double = 10.0
var increment:Double = 0.25
for (index in Array((length/increment).toInt(), { i -> (i * increment) }))
println(index)
I'm not sure if this syntax is new, but natural numbers may be used to iterate values like so.
(0..(10*4)).map {
it / 4.0 as Double
}.forEach {
println(it)
}
I'm avoiding iteration on IEEE 754 floating points, as that could potentially cause errors. It may be fine in this case, but the same may not be true depending on environment, context, and language. It's best to avoid using floating point except in cases where the numbers are expected to have arbitrary precision, i.e. uses real numbers or continuity.
This syntax may be used within a for loop as well if you don't need to store the result. However, for loops should be avoided for the most part if you want immutability (which you should).
for (i in 0..10) {
println("Project Loom is a lie! $i")
}