开发者

Java how to use a double or a string?

开发者 https://www.devze.com 2023-03-04 05:14 出处:网络
Alright so I\'m trying to get the user to input either the word \"random\" or a number (0.01) for a sales tax and my prompt can only use either keybd.next() or keybd.nextDouble() so how would I easily

Alright so I'm trying to get the user to input either the word "random" or a number (0.01) for a sales tax and my prompt can only use either keybd.next() or keybd.nextDouble() so how would I easily do this?

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

Thanks


Assuming keybd is a Scanner

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

You need to use hasNextDouble() to determine if it's a double or not and then act accordingly.

Option B (though you say your requirements exclude this) is to simply read it as a String then do the conversion afterward with Double.valueOf(String) or Double.parseString(String) static methods and catching the NumberFormatException to determine validity.

Edit based on comments from 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
}


You can use Double.parseDouble(String) to convert a string value to a double. If the string does not represent a double value, a NumberFormatException will be thrown.

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


You can use keybd.next() to grab the token as a string. Then check if its a double.

Sample code:

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

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

精彩评论

暂无评论...
验证码 换一张
取 消