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