2011-05-07 15 views
1

好吧,我想让用户输入“随机”一词或一个数字(0.01)的销售税,我的提示只能使用keybd.next()或keybd.nextDouble(),所以如何我会轻易做到这一点吗?Java如何使用double或string?

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

感谢

回答

2

假设keybdScanner

http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html

您需要使用hasNextDouble()以确定它是否是一个双与否,然后采取相应的行动。

选项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 
} 
+0

这是有帮助的,但我不知道如何使用它大声笑。是的,我正在使用扫描仪 – tekman22 2011-05-07 19:11:18

+0

不知道如何使用...什么? – 2011-05-07 19:25:27

+0

我会如何使用它? – tekman22 2011-05-07 19:33:18

0

您可以使用keybd.next()抢令牌作为一个字符串。然后检查它是否一倍。

示例代码:

String input= keybd.next(); 
try{ 
    Double input= Double.parseDouble(input); 
    //execute code with double variable 

} catch (ParseException ex){ 
    //call string handler code 
} 
1

您可以使用Double.parseDouble(String)将字符串值转换为双。如果字符串不代表双精度值,则会抛出一个NumberFormatException

double d; 
if ("random".equals(string)) { 
    d = 4.0; // random 
} else { 
    try { 
    d = Double.parseDouble(string); 
    } catch (NumberFormatException e) { 
    // ! 
    } 
} 
相关问题