Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Java Program - Distance Traveled (Formatting and Decimal Place)

  1. #1
    Junior Member
    Join Date
    Mar 2014
    Posts
    21
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Java Program - Distance Traveled (Formatting and Decimal Place)

    Hi,

    I'm having trouble formatting my output and issues with the decimal places. Here's my code:


    import java.util.Scanner;
    import java.text.DecimalFormat; // Imports DecimalFormat class for one way to round
     
    public class lab3
    {
      public static void main(String[] args)
      {
        String heading1 = "Hour", heading2  = "Distance Traveled";
        int timeElapsed, hour, speed;
        double distanceTraveled;
     
        Scanner keyboard = new Scanner(System.in);
        DecimalFormat dFormatter = new DecimalFormat("0");
     
        // Ask user for the speed of the vehicle
        System.out.print("What is the speed of the vehicle in mph? ");
        speed = keyboard.nextInt();
     
        while(speed < 0)
        {
          System.out.println("The speed may not be a negative number.");       
          System.out.print("What is the speed of the vehicle in mph? ");        
          speed = keyboard.nextInt();
        }
     
        // Ask user for the number of hours vehicle had traveled
        System.out.print("How many hours has it traveled? ");
        timeElapsed = keyboard.nextInt();
     
        System.out.println();
     
        while(timeElapsed < 1)
        {
          System.out.println("The time must be a positive number.");
          System.out.print("How many hours has it traveled? ");
          timeElapsed = keyboard.nextInt();
        }
     
        // Table displaying the total Distance Traveled
        System.out.printf("%4s %22s\n", heading1, heading2);
        System.out.println();
     
        // Hour initialized
        hour = 0;
     
        for(int i=1; i<=timeElapsed; i++)
        {
          hour++;
          if(hour > 1)
          {
            distanceTraveled = hour * speed;
            System.out.printf("%1d %22f\n", hour, distanceTraveled);
          }
          else
            System.out.println(" " + hour + "                " + speed);
        }
      }
    }

    And here's my output (Click on the image since it's pretty small):

    javaIssues.png

    Issue:
    1) The Hours 2 and 3 aren't aligned to 1. How do you fix that?
    2) The 80 and 120 in Distance Traveled have 6 decimal places when it should not have decimals. How do I fix that?

    Feedback is much appreciated!


  2. #2
    Junior Member
    Join Date
    Mar 2014
    Posts
    21
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java Program - Distance Traveled (Formatting and Decimal Place)

    Okay, I was able to fix Issue #1.

    Just had to add some padding to "%d".

    Still can't figure out getting rid of the decimal places for the 80 and 120. I have "import java.text.DecimalFormat;" on there, and don't know what to do from there......

  3. #3
    Member
    Join Date
    Feb 2014
    Posts
    180
    Thanks
    0
    Thanked 48 Times in 45 Posts

    Default Re: Java Program - Distance Traveled (Formatting and Decimal Place)

    There are 2 ways to remove the decimals for issue #2, and they can be done by using just the right formatting in the printf statement.

    1. Specify 0 precision

    "out" in System.out is a PrintStream object. The API doc for PrintStream.printf is at PrintStream (Java Platform SE 7 ) . You'd see that it refers to Formatter (Java Platform SE 7 ) for the format string syntax.

    The general syntax for numeric types is
    %[argument_index$][flags][width][.precision]conversion
    This means in your case you can specify %22.0f so that the output format will have 0 decimal.

    2. Use long type

    Your code assumes the speed and time inputs are integers. If you are sticking with this assumption, you can change distanceTravelled from a double to a long. If you do so, you can then use %22d to print out the distance without decimals.
    Last edited by jashburn; April 11th, 2014 at 02:18 PM. Reason: Place format syntax into code block for readability

  4. #4
    Junior Member
    Join Date
    Mar 2014
    Posts
    21
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java Program - Distance Traveled (Formatting and Decimal Place)

    Quote Originally Posted by jashburn View Post
    There are 2 ways to remove the decimals for issue #2, and they can be done by using just the right formatting in the printf statement.

    1. Specify 0 precision

    "out" in System.out is a PrintStream object. The API doc for PrintStream.printf is at PrintStream (Java Platform SE 7 ) . You'd see that it refers to Formatter (Java Platform SE 7 ) for the format string syntax.

    The general syntax for numeric types is
    %[argument_index$][flags][width][.precision]conversion
    This means in your case you can specify %22.0f so that the output format will have 0 decimal.

    2. Use long type

    Your code assumes the speed and time inputs are integers. If you are sticking with this assumption, you can change distanceTravelled from a double to a long. If you do so, you can then use %22d to print out the distance without decimals.

    Thanks for the reply.

    I just typcasted the double into int (seems to work).

    But, can you give me a sample of how your approach will work, too?

  5. #5
    Member
    Join Date
    Feb 2014
    Posts
    180
    Thanks
    0
    Thanked 48 Times in 45 Posts

    Default Re: Java Program - Distance Traveled (Formatting and Decimal Place)

    Which approach, (1) 0 precision or (2) long type?

    Note that for an elementary program it is fine to workaround issues by typecasting. Later on you will want to declare your variables exactly what they should be, and typecast only when really necessary. In your case, consider the result if the multiplication of hour and speed exceeds the upper limit of an int.

  6. #6
    Junior Member
    Join Date
    Mar 2014
    Posts
    21
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java Program - Distance Traveled (Formatting and Decimal Place)

    Quote Originally Posted by jashburn View Post
    Which approach, (1) 0 precision or (2) long type?

    Note that for an elementary program it is fine to workaround issues by typecasting. Later on you will want to declare your variables exactly what they should be, and typecast only when really necessary. In your case, consider the result if the multiplication of hour and speed exceeds the upper limit of an int.
    #2, I want to know the other way of decimal fomatting. Still a bit confused by it.

  7. #7
    Member
    Join Date
    Feb 2014
    Posts
    180
    Thanks
    0
    Thanked 48 Times in 45 Posts

    Default Re: Java Program - Distance Traveled (Formatting and Decimal Place)

    Quote Originally Posted by jashburn View Post
    2. Use long type

    Your code assumes the speed and time inputs are integers. If you are sticking with this assumption, you can change distanceTravelled from a double to a long. If you do so, you can then use %22d to print out the distance without decimals.
    As mentioned above, it's just a matter of having
    ...
    long distanceTraveled;
    ...
    System.out.printf("%1d %22d\n", hour, distanceTraveled);
    Everything else remains unchanged. With a long you don't need (and cannot) specify precision in the format string, and so %22d can be used. Read through the Conversions section at Formatter (Java Platform SE 7 ) on the use of d and f conversions.

    Remember that long is a 64-bit integer, whereas double is a 64-bit floating point number (and therefore has decimal places that requires the use of precision in the format string.) See Primitive Data Types (The Java™ Tutorials > Learning the Java Language > Language Basics).
    Last edited by jashburn; April 12th, 2014 at 10:02 AM. Reason: Rectified typo

Similar Threads

  1. Distance Traveled problem help
    By rosiems95 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: March 20th, 2014, 03:52 PM
  2. Distance traveled problem
    By Steph2752 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: June 25th, 2013, 11:43 AM
  3. One Decimal Place
    By Akirien in forum Object Oriented Programming
    Replies: 5
    Last Post: August 22nd, 2012, 01:11 AM
  4. How do I change my output to 1 decimal place?
    By dunnage888 in forum What's Wrong With My Code?
    Replies: 16
    Last Post: November 3rd, 2011, 10:39 AM
  5. Logic to implement a program to display decimal place of a number
    By chronoz13 in forum Algorithms & Recursion
    Replies: 2
    Last Post: June 11th, 2009, 04:53 AM

Tags for this Thread