0
Java loan calculator help
Why does the following code not work but the results match the expected output? It works on the first two test cases but fails on test cases 3 to 5. Edit: full code import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int amount = scanner.nextInt(); //your code goes here for(int month = 0; month < 3; month++){ int pmt = amount/100*10; amount = amount - pmt; } System.out.println(amount); } }
7 odpowiedzi
+ 2
Think it has to do with rounding;
If you use this line it works:
int pmt = amount/10;
+ 2
Thanks Paul ... It works but seems odd since I'm using 10% for the pmt rate i.e divide by 100 multiply by 10
+ 1
I don't know exactly your attempt , but with this posted codes :
1) the "amount" variable was missed. It caused the code did not work => Declare the "int amount" before the loop.
2)To avoid initializing variable many times, it's better putting "pmt" variable before the loop .( the code would be more clearer).Then , to debug easier, we can write pmt = (amount/100) *10 ; or pmt= (amount/10)*100 or pmt = amount/10
3)If you want amount varies by amount of month , you can declare month variable before the loop (use Scanner input etc) and the loop will follows it's size.
Hope to help you something
+ 1
This sample code shows the difference between divide by 100 multiply by 10 an divide by 10:
public class Program
{
public static void main(String[] args) {
System.out.println((int)(450/100 * 10));
System.out.println((int)(450/10));
}
}
+ 1
Thanks Paul it makes sense now. While in real world calculations it works, I see that the code converts every calculation into integer instead of just the final result. By understanding this I have changed my method to pmt = amount/(100/10). The 10 represent the % value. This was a great example to learn from.
0
Yes, it about rounding a value. Please note that amount is double, payment should be integer or double or something. There must be a casting mechanism from double to integer.
something like these codes below:)
for (month = 1; month<11; month++)
{
double amount;
payment = rate * (int) amount;
amount = amount - payment
}