Reputation: 1
I'm trying to create a program in java that should calculate the monthly payment and total interest paid on financing for any given purchase. The application should also allow the user to compare the differences between two different payment plans.
What I have
Scanner scan = new Scanner(System.in);
System.out.println("Enter the total cost of the purchase:");
float tPurchase = scan.nextFloat();
System.out.println("Enter your first down payment:");
float Paymentone = scan.nextFloat();
System.out.println("Enter your second down payment: ");
float Paymenttwo = scan.nextFloat();
System.out.println("Enter first lenght of time to pay");
float paylenght = scan.nextFloat();
System.out.println("Enter second length of time to pay:");
float paylength2 = scan.nextFloat();
System.out.println("Enter APR:");
My question is how do I get the program to scan the next number as a percentage. For instance, total purchase 10,000, down payment 3,000, second down 5,000, APR one 1% for three years and APR two 2% for 5 years. No need to tell me how to make it calculate, just how to make it scan as a percentage.
Upvotes: 0
Views: 1121
Reputation:
It depends on how you want the behaviour of your application to be. Will it accept aor to be in the form of xx %
, x.xx
or only xx
?
Then this code will deal with all those three cases:
System.out.println("Enter APR:");
String aprTemp = scan.next();
int apr;
if (aprTemp.contains("%")) {
String aprStr = aprTemp.substring(0, aprTemp.indexOf("%"));
apr=Integer.parseInt(aprTemp);
}else if(aprTemp.matches("[0-9]+")){ // regex for number
apr=Integer.parseInt(aprTemp);
}else if(aprTemp.matches(""^([+-]?\\d*\\.?\\d*)$""){ // regex for float
float aprFloat=Float.parseFloat(aprTemp);
}
Upvotes: 0
Reputation: 5102
There is no different with how to scan the next number as a percentage and what you have done above.
Perhaps the only thing that you need to change is:
System.out.println("Enter the percentage:");
And you may retrieve the input by either:
float percentage = scan.nextFloat(); //or
int percentage = scan.nextInt();
Or if you want user to include %
in their input then you might want to do:
String strPercentage = scan.nextLine();
float percentage = Float.parseFloat(strPercentage.substring(0,strPercentage.length()-1));
Of course you need to validate the user input to match you desired value first.
Upvotes: 1