2011-05-07 1 views
1

D'accord, j'essaye d'obtenir que l'utilisateur saisisse le mot "random" ou un nombre (0.01) pour une taxe de vente et mon invite peut seulement utiliser keybd.next() ou keybd.nextDouble() alors comment ferais-je facilement cela?Java comment utiliser un double ou une chaîne?

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

Merci

Répondre

2

En supposant keybd est un Scanner

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

Vous devez utiliser hasNextDouble() pour déterminer si elle est un double ou non et agir en conséquence.

Option B (si vous dites que vos exigences excluent ce sujet) est de lire simplement comme String puis faire la conversion ensuite avec Double.valueOf(String) ou Double.parseString(String) méthodes statiques et attraper le NumberFormatException pour déterminer la validité.

Modifier en fonction des commentaires de 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

Ceci est utile, mais je ne sais pas comment l'utiliser lol. Oui, j'utilise un scanner – tekman22

+0

Je ne sais pas comment utiliser ... quoi? –

+0

Comment l'utiliser? – tekman22

0

Vous pouvez utiliser keybd.next() pour saisir le jeton comme une chaîne. Ensuite, vérifiez si c'est un double.

Exemple de code:

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

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

Vous pouvez utiliser Double.parseDouble(String) pour convertir une valeur de chaîne à un double. Si la chaîne ne représente pas une double valeur, un NumberFormatException sera lancé.

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