Reputation: 33
If I want the user to input an interest rate in the format of : n% (n is a floating point number).
Given that % is not a valid number to be input, is there a way to nevertheless get the user input and then perform the necessary conversions?
Basically is there a way in which the following code can actually work:
import java.util.Scanner;
public class CanThisWork{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter Annual Interest Rate");
//user input is 5.4% for example
//this is where the problem is because a double data type cannot contain the % symbol:
double rate = input.nextDouble();
System.out.println("Your Annual rate " + rate + " is an error");
}
}
All jokes aside, I would love to get a solution to this predicament
Upvotes: 0
Views: 2942
Reputation: 3600
Because 5.4%
is not a Double
, you would have to use Scanner
methods that reads String as input like next
or nextLine
. But to can ensure that the String that is being read is a double ending with %, you can use hasNext(String pattern)
method.
if (input.hasNext("^[0-9]{1,}(.[0-9]*)?%$")) {
String inputString = input.next();
double rate = Double.parseDouble(inputString.substring(0, inputString.length() - 1));
System.out.println("Your Annual rate " + rate + " is an error");
}
// Pattern explanation
^ - Start of string
[0-9]{1,} - ensure that at least one character is number
[.[0-9]*]* - . can follow any number which can be followed by any number
%$ - ensure that string must end with %
Above code will ensure that only Double
number ending with %
are passed through
Upvotes: 2
Reputation: 729
Since your input is not a double anymore you can't use input.nextDouble()
instead, you need to get it as a string, replace the '%' and then parse it as a double.
double rate = Double.parseDouble(input.nextLine().replace("%",""));
Upvotes: 1
Reputation: 140
I would go with:
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner(System.in);
System.out.println("Enter Annual Interest Rate");
//user input is 5.4% for example
//this is where the problem is because a double data type cannot contain the %
symbol:
String userInput = input.nextLine(); // "5.4%"
double percentage = Double.parseDouble(userInput.replace("%", "")) / 100; // 0.54
//You can now do calculations or anything you want with this value.
//multiplying it with 100 to get it to % again
System.out.println("Your Annual rate " + percentage*100 + "% is an error");
}
Upvotes: 1