在 Java 中使用百分比符号作为用户输入

Using the percentage symbol as a user input in Java

如果我希望用户输入利率格式为:n%(n为浮点数)。

鉴于 % 不是要输入的有效数字,是否有办法获取用户输入然后执行必要的转换?

基本上有没有一种方法可以让下面的代码真正起作用:

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

抛开所有笑话,我很想找到解决这个困境的方法

由于您的输入不再是双精度,因此您不能使用 input.nextDouble(),您需要将其作为字符串获取,替换“%”,然后将其解析为双精度。

double rate = Double.parseDouble(input.nextLine().replace("%",""));

我会选择:

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

因为 5.4% 不是 Double,您必须使用 Scanner 方法将字符串读取为输入,例如 nextnextLine。但是要保证读取的String是双结尾的%,可以使用hasNext(String pattern)方法。

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 %

以上代码将确保只有 Double% 结尾的数字通过