Coversions using math class

public class MeasurementConverterV2_Key
//Purpose of program
    public static void printPurpose( )  //notice that this method is void, nothing is returned
        System.out.println("This program converts to and from");
        System.out.println("English and metric units of measure.");
        System.out.println("=====================================");
    //convert feet to miles
    //the ft parameter receives the value of the feet argument passed from main method.
    public static double convertFeetToMiles(double ft)
        return ft / 5280;     
    //convert miles to feet
    public static double convertMilesToFeet(double mi)
        return mi * 5280;     
    //convert miles to kilometers
    public static double convertMilesToKilometers(double mi)
      return mi * 1.61;      
    //convert kilometers to miles
    public static double convertKilometersToMiles(double km)
        return km / 1.61;    
    //convert pounds to kilograms
    public static double convertPoundsToKilograms(double lbs)
        return lbs / 2.2;  
    //convert kilograms to pounds
    public static double convertKilogramsToPounds(double kl)
        return kl * 2.2;   
    //convert gallons to liters
    public static double convertGallonsToLiters(double gl)
       return gl * 3.79;    
    //convert liters to gallons
    public static double convertLitersToGallons(double lt)
        return lt / 3.79;     
    public static void main(String[ ] args)
        //local variables
        //double miles, feet, inches, pounds, gallons;
       // double kilometers, kilograms, liters;
        //variable declaration and initialization
        printPurpose();                                    //invoke the printPurpose() method
        double feet = 6230;
        double miles = convertFeetToMiles(feet);            //invoke the convertFeetToMiles() static method and pass the feet variable as an argument
        System.out.printf("%8.1f ft. = %7.1f mi. %n", feet, miles);
        miles = 1.9;
        feet = convertMilesToFeet(miles);
        System.out.printf("%8.1f mi. = %7.1f ft. %n", miles, feet);
        miles = 22.3;
        double kilometers = convertMilesToKilometers(miles);
        System.out.printf("%8.1f mi. = %7.1f km. %n", miles, kilometers);
        kilometers = 1000.0;
        miles = convertKilometersToMiles(kilometers);//call method to convert kilometers to miles goes here
        System.out.printf("%8.lf km. = %7.lf mi. %n", kilometers, miles);//print results goes here
        double pounds = 204;
        double kilograms = convertPoundsToKilograms(pounds); //call method to convert pounds to kilograms goes here
        System.out.printf("%8.lf lbs. = %7.lf kl. %n", pounds, kilograms);//print results goes here
        kilograms = 98;
        pounds = convertKilogramsToPounds(kilograms);//declare and initialize the kilograms variable goes here
        System.out.printf("%8.lf kl. = %7.lf lbs. %n", kilograms, pounds);//call method to convert kilograms to pounds goes here
        //print results goes here
        double gallons = 55;//declare and initialize the gallons variable goes here
        double liters = convertGallonsToLiters(gallons);
        System.out.printf("%8.lf gl. = %7.lf lt. %n", gallons, liters);//call method to convert gallons to liters goes here
        //print results goes here
        liters = 2;//declare and initialize the liters variable goes here
        gallons = convertLitersToGallons(liters);//call method to convert liters to gallons goes here
        System.out.printf("%8.lf lt. = %7.lf gl. %n", liters, gallons);//print results goes here
    }//end of main method
}//end of classthis program, when ran, tells me that "UnknownFormatConversionException" and " null(java.util.Formatter). I followed the directions very carefully and made sure everything was spelled correctly; why won't it run passed the point of "kilometers to miles"??

Whenever you get an exception you should do two things:
1.) Look at the stack trace and find the position highest on the stack trace that is your code (i.e. not a class that you didn't write) and look into that line and try to find out what you might be doing wrong there (or just before that)
2.) Look at the API documentation of the Exception class and find out when it's thrown (in this case: look at http://java.sun.com/javase/6/docs/api/java/util/UnknownFormatConversionException.html )
If you still can't figure out the problem post the line where the problem occured.

Similar Messages

  • I can't use Math.class

    I can't use Math.class although I import java.lang.*.
    plz help me.

    and tell us what you mean by "can't use"My father began to work a PC as he was already
    retired. He has been fighting with it ever since.
    Sometimes he calls me for help crying "everthying has
    disappeared!"
    I ask him: "What is 'everything' and what does it
    mean 'disappeared'?"you could then go on to throw a further spanner in the works by asking what "has" means :)

  • Using java math class  for power's SQ rt and rounding.

    Hey all
    ive attempted to use maths class to create a program a user can enter a number and then the output shows
    The number rounded to the nearest integer
    The Square root of the number
    and finaly the number to the power of 6
    So far i have the following code but im a bit thick to what im missing ....
    import java.util.*;
    public class Mathclass
         public static void main(String[] args)
         Scanner kybd = new Scanner(System.in);
         double num = kybd.nextInt(); // kybd is an instance of Scanner
         public static double ceil (double num);
         public static double sqrt (double num);
         public static double exp (double num);
    }}Please be kind i know the outputs arnt there yet but im getting 15 errors in javac
    Thankyou

    Javaman01 wrote:
    i can understand that you feel this way , i just have a lot of programs i need to complete for a portfolio tommorow , so i need all the help i can get.Well, then I guess you started too late. Talk to your teacher that you won't be able to get it done on your own. Start learning your course book or the basic tutorials I posted and try to do the assignments again. I really think you know too little to get this done.
    Javaman01 wrote:
    if you wish not to help the please dont comment as i fear this will put others of helping me when i need it most.I did help you! And you have nothing to say about me posting here or not. Just as I can't stop you from trying to get others to do your homework.
    Javaman01 wrote:
    thankyouYou're welcome.

  • Simple integer generation  using java math classes

    I want to generate a integer which should be combination of 2 integer and one int
    and anytime I call generate it should generate same value for same input and for different combinations it should generate different value.
    for example I passed to the service two integers 24, 25 and one int 76
    assume it generated 242576
    I restart jvm to the service pass the same values mentioned above it should return me same output 242576.
    I want to do this using some math functionality not using string concatinating ?Any suggestions on acheiving this? any help is greatly appreciated.
    miro

    How would you arrive at 242576 from 24, 25 and 76 when performing the operation by hand, on paper? What calculations would you need to perform?
    Your other requirements are standard properties of programming: unless you go out of your way to make it otherwise, methods/functions tend to produce the same output based on the same input.
    BTW, you won't need any math classes for this, just mathematical operators like +, -, *, / etc.

  • Java ME SDK 3.0 Math Class

    Using Eclipse and Java ME SDK 3.0
    When the Application Descriptor configuration is set to use DefaultCldcPhone1 or other emulators in the Java ME SDK 3.0 many of the Math class methods such as Math.sqrt(double arg0) are not available. However if I change the configuration to use a Nokia emulator all the Math class methods become available.
    This issue has just shown up since moving from WTK25 to Java ME SDK 3.0
    Note:
    Under Eclipse/Preferences/Java ME/Device Management the Configuration of all the emulators from the Java ME SDK 3.0 is listed as CLDC-1.0 whereas the other emulators from Nokia and from the Sun Java Wireless Toolkit 2.5 are listed as CLDC-1.1.

    It is related to the configuration of the emulator (CLDC 1.0 or CLDC 1.1)...
    If the configuration is CLDC 1.0 all the floating point data types (float, double, Float, Double) will not be available...
    If you change the configuration to CLDC1.1 , then all the previous types will be available.
    PS: I don't know how to do this in EclipseME

  • Using bigdecimal class

    I was using Gregory-Leibniz series to calculate PI = 4 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + ...
    Something like:
    double pi = 0.0;      
           int limit = 3000000;      
           for (int i = 0, y = 1; i <= limit; y+=2, i++)
                     if (y == 1)
                          pi = 4;
                   else if (i % 2 == 0)
                          pi += (double)4/y;            
                     else
                          pi -= (double)4/y;                                                   
                     System.out.println(String.format("Loop %d: %.20f", i, pi));                                    }Then I realized PI isn't going to be totally accurate according to IEEE Standard for Binary Floating-Point Arithmetic that java math calculation uses, so I was trying to use BigDecimal class (new to me), this is what I got initally...
             BigDecimal pi = new BigDecimal("0.00");           
              int limit = 3000000;
              for (int i = 0, y = 1; i <= limit; y += 2, i++)
                  if (y == 1)
                          pi = new BigDecimal("4.0");
                   else if (i % 2 == 0)
                          pi = pi.add(new BigDecimal( Double.toString( (double) 4 / y )));
                     else
                          pi = pi.subtract(new BigDecimal( Double.toString( (double) 4 / y )));
                        System.out.println(String.format("Loop %d: %s", i, pi.toString()));                                       
    I realize that when I do the 4/y calculations involving both doubles... the result is probably stored according to the IEEE standards which is the thing to avoid... Is that correct? Is my PI result going to be accurate?
    I noticed with this one decimals up to the 22nd place are all filled with some numbers in the calculations compared with the first one involving only double number calculations which had zero's starting around the 15th decimal.
    Something like doesn't work and ends up with arithmeticexceptions...
    pi = pi.subtract(new BigDecimal("4").divide(new BigDecimal(Integer.toString(y))));
    So I'm actually confused about the right way of using BigDecimal class in this type of calculation to get accurate results. I do realize it's an immutable class and probably a bad idea to use it like this 3 million times in a loop.

    quoting from the API documentation on BigDecimal
    "The BigDecimal class gives its user complete control over rounding behavior. If no rounding mode is specified and the exact result cannot be represented, an exception is thrown; otherwise, calculations can be carried out to a chosen precision and rounding mode by supplying an appropriate MathContext object to the operation."
    That explains the arithmetic exceptions.
    You would be advised to choose your scale first, (that would be the number of decimal places that you want to be using for your calculation. ) Then use the BigDecimal constructors that use the scale value. Construct your BigDecimal 4 outside of the loop so that you are not constructing it over and over again. And finally, read the documentation on how the scale of the result will depend upon the scale of the components going in.
    A little reading and possibly re-reading of the documentation will help in the understanding of the BigDecimal class.

  • Trig functions in the Math class

    One of the techniques suggested to master for the Java Programmer exam is using the trigonometry methods in the Math class. Does that mean that on the exam I would need a trigonometry knowledge or is it enough to be familiar with their signature ?

    No trig knowledge - just questions on the Java language, including method signatures. Check out the various mock exams such as at http://www.javaranch.com/certfaq.jsp

  • Why Math class does not have any constructor.

    Math class does not have any constructor.
    But all the classes have a default constructor. Then why the math class is not having any constructor. Is math class having some other constructor or is the default constructor concept applicable only for user defined classes.

    Math class does not have any constructor.
    But all the classes have a default constructor. Then
    why the math class is not having any constructor. Is
    math class having some other constructor or is the
    default constructor concept applicable only for user
    defined classes.You cannot instantiate a new Math object, nor can you extend the Math class. All you can do is use Math's static methods and variables. Its a utility class, thats what its susposed to do.
    JJ

  • Speed of the Math class

    If I am performing a lot of calculations is it best to use a Math class function or write it yourself (best in terms of speed not accuracy).
    e.g. Math.pow(a-b,2) OR (a-b) * (a-b)
    I am grateful for any opinions.

    Your version would allow the compiler to use the fact that the expression is completely knowable at compilation time, providing for a trivial solution for the in-line multiplication approach.
    The version below avoids thatpublic class Test {
        public static void main(String[] args) {
            long start = 0;
            long end = 0;
            long powtime = 0;
            long multtime = 0;
            double x = Double.parseDouble(args[0]);
            double y = Double.parseDouble(args[1]);
            System.out.println("Starting the pow test.");
            start = System.currentTimeMillis();
            for (int i = 0; i < 10000000; i++) {
                double value = (x - y) * (x - y);
            end = System.currentTimeMillis();
            multtime = end - start;
            System.out.println(
                "By using multiplication it took: " + ((double) multtime / 1000) + " seconds.");
            start = System.currentTimeMillis();
            for (int j = 0; j < 10000000; j++) {
                double value = Math.pow((x - y), 2);
            end = System.currentTimeMillis();
            powtime = end - start;
            System.out.println(
                "By using Math.pow() it took: " + ((double) powtime / 1000) + " seconds.");
    }With this I get a 6:1 (1.272 to 0.200) ratio of Math.pow() to inline multiplication time. Still a fairly large ratio.
    Playing with double, int and using increasing larger values of the exponent, the Math.pow() seems to be far slower that multiplication. Of course Math.pow() can handle complex exponents (2.3645463) and take roots while the simple multiplication approach cannot.
    Chuck

  • Question about Math Class

    I have a couple of Java questions I was wondering if anyone could answer:
    1). In this one statement, which takes the greatest common denominator and places it in the variable commom:
    int common = gcd (Math.abs(numerator), denominator);
    A).What is gcd? I looked it up and it's not a reserved word in the math class. In the class that this statement comes from there is no variable, object, or method named gcd. There is also no gcd variable, object, or invoked method in the client code that uses the class that this statement comes from.
    B ). I know that abs is a method of the math class for the absolute value of a number(in this case the number inside the variable numerator.). And I know that when the abs method is invoked it sends the variable 'numerator' as the parameter for the data to take the absolute value of. What I don't understand is the syntax of this statement in regards to how you can take the absolute value of the variable 'denominator' haveing a variable 'numerator' inclosed in the parenthesis and simpley adding a comma to include the variable 'denominator' in the argument to be sent in the invocation of the abs method. It seems like this would be the correct syntax:
    int common = (Math.abs(numerator))/(Math.abs(denominator));
    Can anyone explain the 'int common = gcd (Math.abs(numerator), denominator);'
    statement?
    Thanks,
    -dman

    > A).What is gcd?
    As already been said: it's the Greatest Common Divider.
    Example: fraction 9/24, then gcd(9, 24) == 3.
    >It seems like this would be the correct syntax:
    int common = (Math.abs(numerator))/(Math.abs(denominator));
    Probably the gcd(...) method is used to normalize a fraction whose denominator is always positive. If the fraction is smaller then zero, the numerator is negative. And to caculate the Greatest Common Divider of two numbers, the gcd(...) method needs two positive arguments.
    Google for "Euclid GCD algorithm".

  • Using Math.floor

    When I use Math.floor I get an integer part of a double rigth?
    For exemple >> If I have
    double num = 34.54
    Math.floor(num) will return 34 rigth?
    But this 34 is a double 34.0 or is an integer 34?
    If not an integer, how can I do to get the integer part "34" like a integer number 34 and not like a double 34.0?

    Yes I already did it but it is not working
    Here is the code
    private void confirm(Double list[]){
            int nParcelas = (int)(list[2]);.....
    I call the function confirm from another class, and I pass a list like parameter.
    I have the same fuction but is a list of String and work ok. I get the numbers of this list and make some operations and averything works find...
    But I want to get an item of this list and get its integer part, and it it's not working....

  • How to generate random numbers in a range using random class?

    I know how to use Math.random for this, but how would I generate random numbers using the random class?
    Say I want a number between 40 and 50, inclusive--how would I do this?
    What i have in mind is:
    int randomNumber = random.nextInt(max) + min;
    where max is 50 and min is 40. Is this correct?

    Fredddir_Java wrote:
    I know how to use Math.random for this, but how would I generate random numbers using the random class?
    Say I want a number between 40 and 50, inclusive--how would I do this?
    What i have in mind is:
    int randomNumber = random.nextInt(max) + min;
    where max is 50 and min is 40. Is this correct?What happened when you generated a couple hundred numbers that way? Did you get all the ints in the range you wanted?

  • Using List Class in java.awt / java.util ?

    have a program that:
    import java.util.*;
    List list = new LinkedList();
    list = new ArrayList();
    ... read a file and add elements to array
    use a static setter
    StaticGettersSetters.setArray(list);
    next program:
    import java.awt.*;
    public static java.util.List queryArray =
    StaticGettersSetters.getArray();
    If I don't define queryArray with the package and class, the compiler
    gives an error that the List class in java.awt is invalid for queryArray.
    If I import the util package, import java.util.*; , the compiler
    gives an error that the list class is ambiguous.
    Question:
    If you using a class that exists in multiple packages, is the above declaration of queryArray the only way to declare it ?
    Just curious...
    Thanks for your help,
    YAM-SSM

    So what you have to do is explicitly tell the compiler which one you really want by spelling out the fully-resolved class name:
    import java.awt.*;
    import java.sql.*;
    import java.util.*;
    public class ClashTest
        public static void main(String [] args)
            java.util.Date today    = new java.util.Date();
            java.util.List argsList = Arrays.asList(args);
            System.out.println(today);
            System.out.println(argsList);
    }No problems here. - MOD

  • Creating a triangle using polygon class problem, URGENT??

    Hi i am creating a triangle using polygon class which will eventually be used in a game where by a user clicks on the screen and triangles appear.
    class MainWindow extends Frame
         private Polygon[] m_polyTriangleArr;
                       MainWindow()
                              m_nTrianglesToDraw = 0;
             m_nTrianglesDrawn = 0;
                             m_polyTriangleArr = new Polygon[15];
                             addMouseListener(new MouseCatcher() );
            setVisible(true);
                         class MouseCatcher extends MouseAdapter
                             public void mousePressed(MouseEvent evt)
                  Point ptMouse = new Point();
                  ptMouse = evt.getPoint();
                if(m_nTrianglesDrawn < m_nTrianglesToDraw)
                                int npoints = 3;
                        m_polyTriangleArr[m_nTrianglesDrawn]
                      = new Polygon( ptMouse[].x, ptMouse[].y, npoints);
    }When i compile my code i get the following error message:
    Class Expected
    ')' expectedThe two error messages are refering to the section new Polygon(....)
    line. Please help

    Cannot find symbol constructor Polygon(int, int, int)
    Can some one tell me where this needs to go and what i should generally
    look like pleaseI don't think it is a good idea to try and add the constructor that the compiler
    can't find. Instead you should use the constructor that already exists
    in the Polygon class: ie the one that looks like Polygon(int[], int[], int).
    But this requires you to pass two int arrays and not two ints as you
    are doing at the moment. As you have seen, evt.getPoint() only supplies
    you with a single pair of ints: the x- and y-coordinates of where the mouse
    button was pressed.
    And this is the root of the problem. To draw a triangle you need three
    points. From these three points you can build up two arrays: one containing
    the x-coordinates and one containing the y-coordinates. It is these two
    arrays that will be used as the first two arguments to the Polygon constructor.
    So your task is to figure out how you can respond to mouse presses
    correctly, and only try and add a new triangle when you have all three of its
    vertices.
    [Edit] This assumes that you expect the user to specify all three vertices of the
    triangle. If this isn't the case, say what you do expect.

  • Uploading bitmapData using FileReference class ?

    Hi gurus ;)
    Question nr 1.
    Is it possibly to upload bitmapData to server using
    FileReference class ? How should i approach this issue, is there
    any ready classes available for this purpose. I'm generating
    bitmaps inside my Flash/Flex App and need to store them under users
    profile in server.
    Question nr 2.
    Can i upload files from remote server to another using
    FileReference class
    e.g Somehow like :
    uploadURL = new URLRequest();
    uploadURL.url = "
    http://www.[yourDomain
    fileURL.url = "
    http://www.myLocation.com/myfile.JPG";
    file = new FileReference(fileURL.url);
    file.upload(uploadURL);
    This is just an idea, sure not working ;)
    Any ideas are helpful
    Thx
    iquaaani

    I did a small application that uploads a file to the server
    every hour. If the server response that a login is required to
    upload the file, it goes to a login page to do the login and
    retried to upload the file.
    I got the server response in order to know if the file did
    upload correctly or not (I have to send more form data than just
    the file). I didn't try the mime type since it's not relevant for
    my application and usualy this information is not very trust worthy
    anyways.
    I'm not sure what you mean with exceptions, if you are
    referring to HTTP errors, I think there is an event for that, but I
    used the IOError event for this, and it seems to work good
    also.

Maybe you are looking for