1

So I'm reading Java Concepts Late Edition for my coding class and I just got to the formatting section. There is a practice prompt and I can't get it right and I don't understand why.

The goal is to print a table of prices with prices being print with 2 digits after the decimal point.

import java.util.Scanner;

    public class Table
    {
       public static void main(String[] args)
       {
          Scanner in = new Scanner(System.in);
          System.out.print("Unit price: ");
          double price = in.nextDouble();
    
          System.out.println("Quantity     Price");
          int quantity = 1;
          System.out.printf("%d %.2f", quantity, quantity * price);
          quantity = 12;
          System.out.printf("%d %.2f", quantity, quantity * price);
          quantity = 100;
          System.out.printf("%d %.2f", quantity, quantity * price);
       }
    }

This is my code

Unit price: Quantity     Price
1 19.9512 239.40100 1995.00"**

This is my output

Unit price: Quantity     Price
       1     19.95
      12    239.40
     100   1995.00"

This is the expected output

I don't know what I did wrong. Can someone please help!

blurfus
  • 13,485
  • 8
  • 55
  • 61
NoHobbies
  • 11
  • 1
  • You need to add `%n` to the end for newlines. Also, you have to align the prints by using stuff like `%20s` and `%10d` and similar. Please see [Align printf output in Java](https://stackoverflow.com/questions/15961130/align-printf-output-in-java). – Zabuzard Oct 15 '20 at 16:21
  • I understand the spaces part. The part I'm really confused about is why I'm not getting 2 digits after the decimal point even though I used %.2f – NoHobbies Oct 15 '20 at 17:09
  • What do you mean? You do get 2 digits after the decimal. Even in the output you shared already. `19.9512` is `19.95` and `12` for the next line, because you forgot the newlines `%n` as said before. – Zabuzard Oct 15 '20 at 17:54

1 Answers1

0

Assuming its just missing newlines then look at using the %n

The %n in printf() will automatically insert the host system's native line separator.

Paul Whelan
  • 16,574
  • 12
  • 50
  • 83
  • 1
    It is missing new lines however, it also is being printed out with 4 numbers after the decimal point rather than 2. – NoHobbies Oct 15 '20 at 16:56