'Hi there I want to write a program in kotlin that receives a string from user and prints last two elements of that string twice
val scan = Scanner(System.in)
println("Enter word: ")
var word = scan.next()
var a = word.length-1
var b = word.length-2
//var str = word.substring(b, a)
var str = word.length
word.get(b++)
word.get(a++)
print(word.get(b))
print(word.get(a))
Solution 1:[1]
In Kotlin in is a keyword and needs to be put in backtics for variables with that name. so you could replace
val scan = Scanner(System.in)
with
val scan = Scanner(System.`in`)
However, there's actually no need to make a scanner. Kotlin has the build in function readln to read the input.
furthermore, these line don't do anything useful
word.get(b++)
word.get(a++)
and it actually will bring a outside the range of the word.
also it looks nicer to write word[a] instead of word.get(a). They do exactly the same
It's also recommended to use val instead of var if you're not changing the value aftwards
So I believe this is what you would like:
println("Enter word: ")
val word = readln()
val a = word.length-1
val b = word.length-2
print(word[b])
print(word[a])
print(word[b])
print(word[a])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ivo Beckers |
