Results 1 to 3 of 3
  1. #1
    Jaeela is offline Member
    Join Date
    Mar 2011
    Posts
    21
    Rep Power
    0

    Default Need help with simple java project

    i have made this code to calculate a tip as a starter project. I need to know how to make a JOptionPane display float multiplication. I want to use showMessageDialog, and I would like it to say, "your tip is $X". If I have any errors in my code please tell me about them and how to fix them.
    I also get a loss of precision on line 14

    Java Code:
    import java.lang.String;
    import java.lang.Object;
    import javax.swing.JOptionPane;
    import java.util.StringTokenizer;
    import java.math.BigDecimal;
    public class calc {
      public static void main(String[] args) {
         String input = JOptionPane.showInputDialog(null,
           "Enter the cost of your meal like so: (00.00)",
           "Enter your cost and percent.",
           JOptionPane.PLAIN_MESSAGE);
                float percent = .15;
                float cost = Float.valueOf(input.trim()).floatValue()…
                float tip = percent * cost;
          }
    
    }
    Last edited by Fubarable; 03-28-2011 at 01:14 AM. Reason: code tags added

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

  3. #3
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,762
    Rep Power
    7

    Default

    In Java the default type for integral values is int and for floating point values it is double. Even though you declared percent and cost to be float, the result of the multiplication is a double. You then try to cram that double into a float, hence the loss of precision. Either cast to a float or use double in the first place. Rarely do I see people use float in their code.

Similar Threads

  1. Replies: 11
    Last Post: 03-22-2011, 06:33 AM
  2. Fairly Simple (I think) programming project
    By Glyph in forum Jobs Offered
    Replies: 0
    Last Post: 10-22-2010, 12:16 AM
  3. Simple Project 4 or 5 Hours Pay $100
    By billaaa777 in forum Jobs Offered
    Replies: 0
    Last Post: 08-30-2008, 12:45 AM
  4. [SOLVED] Very Simple 2-3 hour project $50
    By arbit3r in forum Jobs Offered
    Replies: 3
    Last Post: 08-05-2008, 03:20 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •