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

撇开所有笑话,我很想解决这个困境

xiaoyr062285 回答:在Java中将百分比符号用作用户输入

由于5.4%不是Double,因此您必须使用Scanner方法将String读取为输入,例如nextnextLine。但是要确保所读取的字符串是以%结尾的双精度字符串,可以使用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结尾的%个数字

,

由于您的输入不再是双精度型,因此不能再使用[global] workgroup = WORKGROUP realm = EXAMPLE.LOCAL dedicated keytab file = FILE:/etc/samba/samba.keytab kerberos method = dedicated keytab log file = /var/log/samba/log.%m security = ads [homes] browsable = no writable = yes [shared] path = /shared writable = yes browsable=yes write list = @admins ,您需要以字符串形式获取它,替换'%',然后将其解析为双精度型。

input.nextDouble()
,

我会选择:

    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");
}
本文链接:https://www.f2er.com/2844929.html

大家都在问