1

printf関数を使用して、摂氏から華氏への変換テーブルを作成しています。

私のメモでは、printf の % の直後に ^ フラグを使用して、出力を中央に配置できるはずであることがわかります。しかし、プログラムを実行すると、Netbeans から常にエラー メッセージが表示されます。

誰かが私の出力を中心に置くのを手伝ってくれるかどうか疑問に思っていました. 私のコードは次のとおりです。

すでに回答済みの質問に目を通しました。しかし、今まで授業で教えてもらった内容と一致しておらず、使えません。

どんな助けでも大歓迎です。

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

「^」は最後に配置されます。

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

----しかし、そのコードを入力すると、Netbeans でエラーが発生します。

4

1 に答える 1

0

javadocを見るとFormatter、Java には printf の出力を中央に配置するフラグがなく、フラグもありません^

あなたのメモはおそらく、Cのprintf機能の「高度な」Javaポートに付属するLavaライブラリを参照しています。フラグに関するセクションの下の Lava仕様^で指定されているように、出力をセンタリングするためのフラグです。

SO の他の場所で指定されているように、 Apache Commons Lang LibraryのStringUtils.centerメソッドを使用するか、独自のメソッドを考案できます。

于 2013-09-29T18:32:49.163 に答える