Kotlin User Input using readline() - kotlin

i'm trying to get multiple input from user and i'm using readlint()!! following by for loop when i go try to print those input back it only shows one output which is the last one...
And i have tried .split(' ') method which is kinda better than for Loop trick but i want my program more better..
1- it take input from new line(for Multiple inputs)
2- it print out all user input
here's my code and it prints out in one line
fun getTheData() {
try{
val(a,b,c) = readLine()!!.split(' ')
println("$a , $b, $c")
}catch (ex: IndexOutOfBoundsException){
println("invalid")
}
}

Here you're only reading one line.
The split() function simply splits your single line into multiple parts separated by a single whitespace.
In short, if you input 1 2 3 in one line, it will print the 3 numbers. However, if you input several lines, you'll only get the first line, as you never read other lines (only one call to readLine()).
In order to read more lines, you do need some sort of loop, like:
fun main() {
while(true) {
val line = readLine()!!
println(line)
}
}

Related

Read one or two variables alternately in one line

I have declared 2 variables to read from console but on other case i want to read just one of them but i can't.
My code:
print("Enter two numbers in format: {source base} {target base} (To quit type /exit) ")
val (sourceBase, targetBase) = readLine()!!.split(" ")
`I can't type /exit because i've got IndexOutOfBoundsException.
Any tips?
Edit: Thank you all for respond, especially lukas.j, it's working now.
Add a second element, an empty string, if the splitted readLine() contains less than 2 elements:
val (sourceBase, targetBase) = readLine()!!.split(" ").let { if (it.size < 2) it + "" else it }

how to read mutliple lines of string into one variable using readln() in kotlin?

example:
a variable
val str = readln().replace("[^A-Za-z0-9 ] \\s+".toRegex(),"").trim()
should read multiple lines of input value, input value will be like this
heading
----------
topic1
topic2
or like this
heading
-------
a) topic1
b) topic2
input may contain special characters or tabs or spaces we need to remove them also
I don't know what your Regex is trying to do, but that's not really your question.
How do you know when the user has finished their input - a special word or an empty line?
Assuming an empty line, here's how you can get all the content
println("Enter something:")
var lines = ""
do {
val line = readLine()
lines += "${clean(line)}\n"
} while (!line.isNullOrBlank())
println("User input:\n$lines")
private fun clean(line: String?): String? {
return line?.replace("[^A-Za-z0-9 ] \\s+".toRegex(),"")?.trim()
}

kotlin \n adds an extra space in output

So i have a string text = "" and when i want to increment i use text+= "something", but i need to make a break line because i will write that text a couple times repeated, but when i do text+="\n" it adds the spaces between the "something" texts but after that it adds another space that i dont want.
I would not do it iteratively. So instead of using a loop, you can use joinToString for that, like this:
lines.joinToString(separator = "\n")
val result = string.substringBeforeLast("\n")
This might help!
fun main() {
var string=""
for (line in 0 until 4){
string += "Something"
if (line!=3){
string+="\n"
}
}
print(string)
}

Check if one of the values contain line breaks

i am new to Kotlin
I would like to iterate through my map and check if there is line break anywhere and if so return false, what would be the best approach. I am not sure if i can use mathches , but yeh basically if. lets say there is a string value "Hello" +c /n + "world": i would like to return false
fun isLineBreakExist(languageMap: MultiLanguageString){
languageMap.forEach { (value) -> value.matches("") }
}
}

How to get the last input ID in a textfile?

Can someone help me in my problem?
Because I'm having a hard time of on how to get the last input ID in a text file. My back end is a text file.
Thanks.
this is the sample content of the text file of my program.
ID|CODE1|CODE2|EXPLAIN|CODE3|DATE|PRICE1|PRICE2|PRICE3|
02|JKDHG|hkjd|Hfdkhgfdkjgh|264|56.46.54|654 654.87|878 643.51|567 468.46|
03|DEJSL|hdsk|Djfglkdfjhdlf|616|46.54.56|654 654.65|465 465.46|546 546.54|
01|JANE|jane|Jane|251|56.46.54|534 654.65|654 642.54|543 468.74|
how would I get the last input id so that the id of the input line wouldn't back to number 1?
Make a function that read file and return list of lines(string) like this:
public static List<string> ReadTextFileReturnListOfLines(string strPath)
{
List<string> MyLineList = new List<string>();
try
{
// Create an instance of StreamReader to read from a file.
StreamReader sr = new StreamReader(strPath);
string line = null;
// Read and display the lines from the file until the end
// of the file is reached.
do
{
line = sr.ReadLine();
if (line != null)
{
MyLineList.Add(line);
}
} while (!(line == null));
sr.Close();
return MyLineList;
}
catch (Exception E)
{
throw E;
}
}
I am not sure if
ID|CODE1|CODE2|EXPLAIN|CODE3|DATE|PRICE1|PRICE2|PRICE3|
is part of the file but you have to adjust the index of the element you want to get
, then get the element in the list.
MyStringList(1).split("|")(0);
If you're looking for the last (highest) number in the ID field, you could do it with a single line in LINQ:
Dim MaxID = (From line in File.ReadAllLines("file.txt")
Skip 1
Select line.Split("|")(0)).Max()
What this code does is gets an array via File.ReadAllLines, skips the first line (which appears to be a header), splits each line on the delimiter (|), takes the first element from that split (which is ID) and selects the maximum value.
In the case of your sample input, the result is "03".