好吧,所以我试图让用户输入“随机”一词或销售税的数字 (0.01),我的提示只能使用 keybd.next() 或 keybd.nextDouble() 所以我怎样才能轻松做到这一点?
public void calculateSalesReceipt(){
System.out.println("Enter the sales tax percentage (ex. 0.08 for 8%) or type \"random\" for a random number: ");
double tax = keybd.nextDouble();
if(tax < 0){
System.out.println("You must enter a value equal to or greater than 0!");
}else{
getFinalPricePreTax();
total = total;
taxcost = total * tax;
double finaltotal = total * taxcost;
System.out.println("Sales Receipt");
System.out.println("-------------");
for(Item currentProduct : shoppingBag){
System.out.println(currentProduct.getName() + " - " + currentProduct.getUnits() + " units " + " - $" + currentProduct.getCost());
}
System.out.println("Total cost: $" + total);
System.out.println("Total tax: $" + taxcost);
System.out.println("Total cost with tax: $" + finaltotal);
}
谢谢
最佳答案
假设 keybd
是一个 Scanner
http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html
您需要使用 hasNextDouble()
来确定它是否为 double ,然后采取相应的行动。
选项 B(尽管您说您的要求排除了这一点)是简单地将其作为 String
读取,然后使用 Double.valueOf(String)
或 Double.parseString(String)
静态方法并捕获 NumberFormatException
以确定有效性。
根据 OP 的评论进行编辑:
System.out.println("Enter the sales tax ... blah blah");
if (keybd.hasNextDouble())
{
double tax = keybd.nextDouble();
// Do double stuff
}
else
{
// Get String and Do string stuff
}
关于Java如何使用double或string?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5923274/