Java-如何使用美元符号
在我的一个代码中,我希望客户能够输入他们想投入机器的钱的数量,机器计算出要返还给客户多少钱。但是,我希望这样,如果客户在支付的金额之前没有输入“$”,系统会告诉他们再试一次。我不知道怎么做。这是到目前为止我的代码Java-如何使用美元符号,java,Java,在我的一个代码中,我希望客户能够输入他们想投入机器的钱的数量,机器计算出要返还给客户多少钱。但是,我希望这样,如果客户在支付的金额之前没有输入“$”,系统会告诉他们再试一次。我不知道怎么做。这是到目前为止我的代码 double customerPayment; System.out.print("$ " + purchasePrice + " remains to be paid. Enter coin or note: "); customerPayment = nextDouble(); /
double customerPayment;
System.out.print("$ " + purchasePrice + " remains to be paid. Enter coin or note: ");
customerPayment = nextDouble();
//i want to tell the customer if they DONT input a '$' that they must try again
有很多方法可以通过字符串实现这一点。我的建议是:不要试图从替身上读一个$ 您可以这样做:
double readCustomerPayment() {
Scanner scanner = new Scanner(System.in);
String inputStr = scanner.nextLine();
scanner.close();
if (!inputStr.startsWith("$")) {
return readCustomerPayment();
}
String doubleStr = inputStr.substring(1);
return Double.parseDouble(doubleStr);
}
您必须使用字符串类型来扫描输入 如果扫描的输入字符串是enteredString,则以下代码段将解析该字符串并提供一个双精度值
if(enteredString.startsWith("$")){
Double customerPayment = Double.parseDouble(enteredString.substring(1));
}
然后你必须输入一个字符串。
如果(!enteredString.contains($){System.out.print(“重试”);}
根据问题,“$”符号在金额之前,使用“startsWith”不是比“contains”更合适吗?@sendhilkumaralasundaram是的,谢谢。我第一次误解了。@Sendhikumaralasundaram非常感谢!