gpt4 book ai didi

java - COMP SCI 101 - 使用 Printf 将字段居中

转载 作者:行者123 更新时间:2023-12-01 04:19:34 24 4
gpt4 key购买 nike

我正在使用 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 中收到错误。

最佳答案

如果你查看Formatter javadoc,Java没有将printf的输出居中的标志,并且没有^标志。

您的笔记可能指的是 Lava library ,它附带了 C printf 函数的“高级”Java 端口。正如 Lava specification 中所指定的那样在标志部分下,^ 是居中输出的标志。

正如 SO 中其他地方所指定的,您可以使用 StringUtils.center方法来自 Apache Commons Lang Library ,或设计a method of your own .

关于java - COMP SCI 101 - 使用 Printf 将字段居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19081329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com