Search code examples
javabluej

Java program doesn't show the desired output


I am new to Java programming. I've been trying to write some code in Java but the desired output (or the output which must come) is never received. (Refer the code from here)For example, if I enter quantity 4 for the category 'w' then according to me it must give the output as $2940 but instead of the output '$2940' it displays the output as $38480. Please help and thanks in advance...

case 'A':
case 'a':
    System.out.println("You selected NOS Tank.");
    int price;
    double quantity;
    double variant=0; 
    System.out.println("Select the variant: ");                                                    
    System.out.println("Enter 'D' without apostrophe for dry or 'W' for wet");
    variant=xss.next().charAt(0);                                                                  
    if (variant=='D' || variant=='d'){                
        System.out.println("The price of dry nitrous oxide system is: $600");                
    } else if (variant=='w' || variant=='W'){                
        System.out.println("The price of wet nitrous oxide is: $740");               
    } else {
        System.out.println("Invalid input.");                                                      
        System.out.println("Exiting......");
        System.exit(0);
    }
    System.out.println("Enter the quantity: ");
    quantity=xss.next().charAt(0);
    if (variant=='D' || variant=='d') {
        System.out.println("The amount payable is: $"+(quantity*600));
    } else if (variant=='w' || variant=='W') {
        System.out.println("The amount payable is: $"+(quantity*740));
    } else {
        System.out.println("Invalid input.");                                                      
        System.out.println("Exiting......");
        System.exit(0);
    }
    break;

Solution

  • You are doing

    quantity=xss.next().charAt(0);
    

    Now character at this location is 4. But when you store it in int, it will take it's ASCII value which is 52. May be try

    quantity=Integer.parseInt(xss.next().charAt(0)+"");
    

    Or

    quantity=Integer.parseInt(String.valueOf(xss.next().charAt(0)));