1

I am creating a Celsius to Fahrenheit conversion table using the printf function.

In my notes, I see that I should be able to center the output using the ^ flag immediately after the % for printf. However, Netbeans always gives me an error message when I run the program.

I was wondering if anybody can help me center my output. My code is as follows.

I have looked through questions that have already been answered. However, they do not correspond with what I was taught in class thus far and as such - I cannot use it.

Any help would be greatly appreciated.

public class CelsToFahrTable {

/**
 * Main argument prints a Celsius to Fahrenheit conversion table
 * using integer Celsius degrees from 0 to 40
 */
public static void main(String[] args) 
{
    // declare variables
    double Cels; //control variable (Celsius Temperature)

    System.out.printf("%10s\t%10s%n", "Celsius", "Fahrenheit"); 
    //prints headers Celsius and Fahrenheit at the top to signify what the data
    //below means. Celsius should take up 10 columns then tab to Fahrenheit
    //which again takes up 10 columns

    for ( Cels = 0; Cels <= 40; Cels++)
        //creates count-controlled loop using for statement
        //Cels initialized to 0, continues expression until 40 and increments
        //by 1 degree each time

        System.out.printf("%10.0f%10.1f%n", Cels, 1.8*Cels+32.0);
    //creates table showing Celsius temperature followed by its corresponding
    //Fahrenheit temperature. Celsius temp is 10 columns with no decimals.  
    //Fahrenheit temp is 10 columns with a 1 decimal precision.

    //Note: I tried to center each field using "^" but it gave me an error 
    //every time

}//end main

The "^" would be placed in the final:

System.out.printf ("%^10.0f%^10.1f%n", Cels, 1.8*Cels+32.0" 

----However when I type that code I get an error in Netbeans.

Pointy
  • 405,095
  • 59
  • 585
  • 614
zhughes3
  • 467
  • 10
  • 22

1 Answers1

0

If you look through the Formatter javadoc, Java does not have a flag to center the output of printf, and there is no ^ flag.

Your notes are probably referring to the Lava library, which comes with "an advanced" Java port of the C printf function. As specified in the Lava specification under the section on flags, ^ is the flag for centering output.

As specified elsewhere on SO, you can use the StringUtils.center method from the Apache Commons Lang Library, or devise a method of your own.

Community
  • 1
  • 1
AbdullahC
  • 6,649
  • 3
  • 27
  • 43
  • 1
    Thank you very much for your information. Through this post, I learned that ^ is not a valid flag. Since, my professor has not taught us how to use the StringUtils.center method, I won't use it. But I did tinker around with the column width in the final printf I used in my code to make it appear centered. And it looks pretty good. – zhughes3 Sep 29 '13 at 19:07