0

Im having a bit of trouble with trying to print an array using printf, Im doing it through OOP. Im passing random salaries for 10 sales Reps.

Here is what I've got so far...

public void printArray()
{
    for(int salesRep = 0; salesRep < salary.length; salesRep++)
    {
        System.out.printf("Sales Rep %d%n", "%4d Current Salary: %2.f", (salesRep + 1), salary[salesRep]);
    }
}

This is the output I'm getting...

enter image description here

However I'm trying to get it to display like this... enter image description here

Any help would be appreciated.

3
  • I never coded a single line of Java in my life, but it looks to me that you have 3 (maybe 4) format specifiers (%d%n %4d %2.f) and only 2 piece of data ((salesRep + 1) and salary[salesRep]). Commented Apr 9, 2016 at 16:32
  • &d&n is for a decimal integer and new line (which I'm counting as 1 specifier) %4d is to tab across and %2.f i think is to have to 2 decimal places? Commented Apr 9, 2016 at 16:36
  • 1
    The signature of printf() is printf(String format, Object... args). But you have two format strings, and then 2 arguments, instead of 1 format string and 3 arguments. Commented Apr 9, 2016 at 16:43

2 Answers 2

2

I think it needs to be something like this:

System.out.printf("Sales Rep %d Current Salary: %.2f %n", (salesRep + 1), salary[salesRep]);

Each line that will be printed is inside the double quotes. The values that follow replace the %d and %f respectively that are inside the quotes (you can choose your own width/spacing). The %n inside the quotes will create a newline.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to combine your format strings into a single string as the first parameter. You also have one too many specifiers, so remove %4d. And change the last specifier to %.1f -- the period (.) must come before the digit (1).

More info on how to use printf in java: https://www.cs.colostate.edu/~cs160/.Spring16/resources/Java_printf_method_quick_reference.pdf

Example:

public class Test {
  public static void main(String []args) {
    printArray();
  }

  public static void printArray() {
     double salary[] = {35000.0, 45000.0, 2000.0, 110000.0, 5000.0
                        35001.0, 18999.0, 95000.0, 9999.0, 65000.0};
     for(int salesRep = 0; salesRep < salary.length; salesRep++) {
       System.out.printf("Sales Rep %d\tCurrent Salary: %.1f\n",
                         (salesRep + 1), salary[salesRep]);
    }
  }
}

Output:

Example output

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.