I'm new at kotlin. Now I'm trying to code a Phone Bill Calculator, when I have to charge user 0.25 for every minute they were over their plan, and 15% tax on subtotal. I can't find the 15% tax.
import java.util.*
fun main(args: Array<String>) {
var numberOfCalls: Int
val phoneBill: Float
val thetax: Float = 15f
val scan = Scanner(System.`in`)
print("Enter the Total Minutes of Calls Made this Month: ")
numberOfCalls = scan.nextInt()
if (numberOfCalls <= 60) phoneBill = 10f else {
numberOfCalls = numberOfCalls - 60
phoneBill = ((10 (numberOfCalls * 0.25 )).toFloat() (thetax/100))
}
println("\nTelephone Bill this Month = $phoneBill")
}
CodePudding user response:
Instead of using this formula bill = total total * tax
you was using this bill = total taxPercentage
which is wrong, you can calculate it like that and have theTaxAmount
separately ( you can use it somewhere ):
fun main(args: Array<String>) {
var numberOfCalls: Int
val phoneBill: Float
val theTaxPercentage: Float = 0.15f
val scan = Scanner(System.`in`)
print("Enter the Total Minutes of Calls Made this Month: ")
numberOfCalls = scan.nextInt()
if (numberOfCalls <= 60) phoneBill = 10f else {
numberOfCalls -= 60
val phoneBillWithoutTax = (10 (numberOfCalls * 0.25 )).toFloat()
val theTaxAmount = phoneBillWithoutTax * theTaxPercentage
phoneBill = phoneBillWithoutTax theTaxAmount
}
println("\nTelephone Bill this Month = $phoneBill")
}
CodePudding user response:
Your algebra error is that you didn't multiply the tax by anything. You just added it like it was a flat rate of 15 cents. A tax by percentage is multiplied by the total amount. And an algebra tip: it's less math (and less code) to multiply something by 115% (1.15
) than it is to figure out what 15% would be and add it to the original value.
I find it is easier (and has clearer code) to solve a problem by doing minimal number of steps at a time instead of setting up all your variables at the start and then modifying them. Create/initialize what you need only immediately before you will use it. Basically, if you can write your logic out of val
s and no var
s, usually this will be a cleaner solution.
fun main(args: Array<String>) {
print("Enter the Total Minutes of Calls Made this Month: ")
val scan = Scanner(System.`in`)
val numberOfMinutes = scan.nextInt()
var excessMinutes = numberOfMinutes - 60
if (excessMinutes < 0) {
excessMinutes = 0
}
val bill = 10 excessMinutes * 0.25
val taxedBill = bill * 1.15
println("\nTelephone Bill this Month = $taxedBill")
}
The four lines of code for excessMinutes
can be shortened as below, but I wrote it out verbosely since you are just learning how the basic logic works, and if you're doing this for a class, the teacher might not expect you to be using helper functions like that yet.
val excessMinutes = max(0, numberOfMinutes - 60)