Search code examples
javajava.util.scannersymbols

Using the percentage symbol as a user input in Java


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


Solution

  • 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");
    }