Need help with this java code

Discussion in 'Programming' started by Andy Lippis, Mar 19, 2013.

  1. #1
    I need to take what ever the answer that is given and make it a variable.


            if (policeHoldersAge < 25)
                System.out.println("Age-base premium adjustment:    $" + 0.5 * basePremiumPayable);
         
            else if (policeHoldersAge  >= 25 && policeHoldersAge <=34)
                System.out.println("Age-base premium adjustment:      $" + 0.2 * basePremiumPayable);
           
            if (policeHoldersAge >= 35)
                System.out.println("Age-base premium adjustment:    $" +  basePremiumPayable);
    Code (markup):
    How do i do this as i will need it for a calculation that will be made later.
     
    Andy Lippis, Mar 19, 2013 IP
  2. pHrEaK

    pHrEaK Active Member

    Messages:
    147
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    53
    #2
    If I understand correctly you want to obtain an input value from a user and store it as a variable to be used by the program? Since your utilizing the command line I suggest you take a look at the system.readline() method. This link should prove to be useful: http://stackoverflow.com/questions/8560395/how-to-use-readline-in-java
     
    pHrEaK, Mar 19, 2013 IP
  3. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #3
    Java's not entirely my bag, but it's really just another C flavor of the month -- so I would probably go about it thus:
    float ageBasePremiumAdjustment = (
    	policeHoldersAge < 25 ? 0.5 : (policeHoldersAge <35 ? 0.2 : 1)
    ) * basePremiumPayable;
    
    System.out.println("Age-base premium adjustment:    $" + ageBasePremiumAdjustment);
    Code (markup):
    I guessed on the variable type, you'd want to make that match. I left the System.out in just so we can see it's working. Making an inline-expression that determines the multiplier simplifies the code down a lot -- no need to say IF when we already know a result so it's maximum two conditions instead of one, and moving the multiply AFTER means we don't say the muliply more than once.

    Untested code, but that should work.

    -- edit -- I should probably explain that evaluation... Basically this:
    policeHoldersAge < 25 ? 0.5 : (policeHoldersAge <35 ? 0.2 : 1)

    Is the same as saying If it's less than 25, use 0.5, else if it's less than 35, use 0.2, else use one. When you make IF or inline expressions testing for values, try not to check the same thing more than once -- if you've already trapped the low, you don't need to check it again, if you already trapped the middle, you don't need to check that again either.
     
    Last edited: Mar 19, 2013
    deathshadow, Mar 19, 2013 IP