我如何使用System.out.printf? [英] how do I use System.out.printf?

查看:114
本文介绍了我如何使用System.out.printf?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的老师希望我们以格式方法(最底层)显示我们的值,但问题是我们有一个子,她没有告诉我们如何使用它,我的老师不太有帮助。任何建议或帮助将不胜感激。

My teacher wants us to display our values in the format method (at the very bottom) but the problem is we had a sub and she didn't show us how to use it and my teacher is being less than helpful. Any advice or help would be greatly appreciated.

public class SphereCalculations
{
public static void main(String[] args)
{
   //define variables
   double circumference = 0;
   double area = 0;
   double volume = 0;
   double surfacearea = 0;
   double radius = 0;
   Scanner scan = new Scanner (System.in);
   DecimalFormat dFmt = new DecimalFormat("0.0000");

   //prompt for radius
   System.out.println("Enter the sphere's radius: ");
   radius = scan.nextDouble();

   //calculate values
   circumference = 2 * Math.PI * radius;
   area = Math.PI * (Math.pow(radius, 2));
   volume = ((4 / 3) * Math.PI) * Math.pow(radius, 3);
   surfacearea = (4 * Math.PI) * Math.pow(radius, 2);

   //Display values with println and DecimalFormat
   System.out.println("Using Println");
   System.out.println("The radius: " + radius);
   System.out.println("Circumference: " + dFmt.format(circumference));
   System.out.println("Area: " + dFmt.format(area));
   System.out.println("Volume: " + dFmt.format(volume));
   System.out.println("Surface Area: " + dFmt.format(surfacearea));

   //Display values with format method
   System.out.printf();


推荐答案

以下是一些例子:

(嵌入式注释中的输出显示在双引号内)

注意:System.out。 format()= System.out.printf()

Note : System.out.format() = System.out.printf()

import java.util.Calendar;
import java.util.Locale;

public class TestFormat {

    public static void main(String[] args) {
      long n = 461012;
      System.out.format("%d%n", n);      //  -->  "461012"
      System.out.format("%08d%n", n);    //  -->  "00461012"
      System.out.format("%+8d%n", n);    //  -->  " +461012"
      System.out.format("%,8d%n", n);    // -->  " 461,012"
      System.out.format("%+,8d%n%n", n); //  -->  "+461,012"

      double pi = Math.PI;

      System.out.format("%f%n", pi);       // -->  "3.141593"
      System.out.format("%.3f%n", pi);     // -->  "3.142"
      System.out.format("%10.3f%n", pi);   // -->  "     3.142"
      System.out.format("%-10.3f%n", pi);  // -->  "3.142"
      System.out.format(Locale.FRANCE,
                        "%-10.4f%n%n", pi); // -->  "3,1416"

      Calendar c = Calendar.getInstance();
      System.out.format("%tB %te, %tY%n", c, c, c); // -->  "May 29, 2006"

      System.out.format("%tl:%tM %tp%n", c, c, c);  // -->  "2:34 am"

      System.out.format("%tD%n", c);    // -->  "05/29/06"
    }
}

来源

这篇关于我如何使用System.out.printf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆