格式化我的输出

时间:2015-09-15 00:40:12

标签: java formatting

我应该创建一个类和一个运行器,它接收4个变量并使用它们来计算线的斜率。我的问题是我不知道如何格式化我的输出,所以我没有这么长的小数。我应该使用的格式输出是:out.println(String.format(“%。3f”,dec ))这是我班级的代码。

public class Line
 {
  private int xOne;
  private int yOne;
  private int xTwo;
  private int yTwo;
  private double slope;

 public Line(int x1, int y1, int x2, int y2)
 {
  int xOne = x1;
  int yOne = y1;
  int xTwo = x2;
  int yTwo = y2; 

 }

 public void setCoordinates(int x1, int y1, int x2, int y2)
 {
  xOne = (int) x1;
  yOne = (int) y1;
  xTwo = (int) x2; 
  yTwo = (int) y2;

 }

public void calculateSlope( )
{
   slope = (yTwo - yOne) / (xTwo - xOne); 


}

public void print( )
{

    System.out.println( "The slope is " + slope); 

  }
 }

这是我的跑步者的代码。

  public class LineRunner
 {
 public static void main( String[] args )
  {
  Line test = new Line(1,9,14,2);
  test.calculateSlope();
  test.print();

  test.setCoordinates(1,7,18,3);
  test.calculateSlope();
  test.print();
  }
 }

任何帮助都会很棒!

1 个答案:

答案 0 :(得分:0)

您可以使用DecimalFormat

DecimalFormat twoDForm = new DecimalFormat("#.##");
System.out.println(Double.valueOf(twoDForm.format(slope)));

如果需要,您甚至可以设置想要进行舍入的方式,例如:

twoDForm.setRoundingMode(RoundingMode.CEILING);