I may be misunderstanding the question, because it seems pretty basic…
The code in the question reads a number from the user into the variable input
, but does nothing with it. So I suspect what you want to do is println(tax(input))
.
However, if you try that, you'll get a compile error:
Type mismatch.
Required: Double
Found: String?
input
is a String (or null if end-of-file), but your tax()
function needs a Double
number. So what you have to do is to convert the String to a number. The easiest way is by calling the String's toDouble()
method.
If you do that, you'll get another compiler error, because you're not handling the possibility that input
could be null (and you can't call toDouble()
on a null). So you have to check for that first, e.g.:
if (input != null)
println(tax(input.toDouble())
I think that gives what you want.
But there are many improvements worth making, e.g.:
- You probably don't want to be using a floating-point binary type like
Double
, as that can't store decimal fractions exactly. (It rounds to the nearest decimal when displaying, which often masks the problem, but it comes back to bite you in many subtle ways.) Instead, you could use the BigDecimal
type which doesn't have that problem.
- The tax rate should be a constant, so you don't have to repeat it anywhere else.
- You could include a prompt to the user, and then extra information in the output by using a string template (as @Sid suggests). In that case, it's best to store the price to avoid having to convert it twice.
- Since you're not modifying
input
after creating it, it's safer to make it an immutable val
rather than a var
.
- You can use the shorter expression form of the
tax()
function.
With all those changes, it might look something like this:
val TAX_RATE = BigDecimal("0.24")
fun main(args: Array<String>) {
println("Enter the price:")
val input = readLine()
if (input != null) {
val price = input.toBigDecimal()
val taxPercentage = TAX_RATE.scaleByPowerOfTen(2)
println("€$price * tax @ $taxPercentage% = €${tax(price)}")
}
}
fun tax(x: BigDecimal) = TAX_RATE * x
I'm assuming the price is in euros; in a more sophisticated program the currency would probably be passed/input with the price. And in practice, tax calculations are usually far more complex (e.g. handling items which have different rates, zero rates, or are exempt from tax, and tax may not be payable anyway depending who the buyer is)…
(By the way, ‘tax’ is not an abbreviation, so isn't usually capitalised.)