I have a problem with a console application in Kotlin. The program reads two variable in the same line. If I'm not wrong, this can be done only with readLine()!!.split(" ") The problem is the next. It needs 2 input. When only one input is provided, the program crashes with out of bounds because the second variable is not entered. In the task the program must exit with the input /exit. I don't know how to do it. Entering a space for the second input is not an option because the test not accepts it. Thanks in advance.
Enter two numbers in format: {source base} {target base} (To quit type /exit) > 36 10 Enter number in base 36 to convert to base 10 (To go back type /back) > abcde Conversion result: 17325410
Enter two numbers in format: {source base} {target base} (To quit type /exit) > /exit
CodePudding user response:
I won't answer to the whole problem you've stated, but just address your OutOfBoundException
, because it looks like an homework question to me.
If you don't mind an OutOfBoundException
being thrown for inputs other than /exit
, the following might work for you.
val line = readln().trim()
if (line == "/exit") {
// exit, e.g. through System.exit(0) or other means
} else {
val bases = line
.split(" ")
.map { it.toInt() }
val (sourceBase, targetBase) = bases
// carry on with your program ...
}
You may want to validate the inputs other than /exit
explicitly, before splitting the input and converting it to numbers.
In this simple case, you can utilize regular expressions to validate the user input. Something along the following lines may work for you.
require(line.matches("""^\d \d $""".toRegex())) {
"You must enter two integer numbers delimited by a single space character!"
}
In case you haven't come in touch with regular expressions (regex) yet, I'll take apart the above for you:
^
- validate from the start of a line\d
- matches any digit\d
- matches any digit$
- validate until the end of the line
I consciously left out any control flow structures, as these do not correlate to the OutOfBoundException
.