Koordinatengrafik mit Java
HomeAufgabenDruckenJava-Online

Formatierte Ausgabe

Die Ergebnisse der Berechnungen in Java werden in der Regel mit mehreren Dezimalstellen angezeigt. Folgende Beispiele zeigen, wie man die Anzahl der Stellen und die Position der ausgegeben Werte formatieren kann.

Beispiel 1: Werteausgabe mit drei Dezimalstellen

// FormatEx1.java

import ch.aplu.util.*;
import java.text.*;

public class FormatEx1 extends Console
{
  FormatEx1()
  {
    DecimalFormat df = new DecimalFormat("#0.000");
 
    for (int i = 0; i < 100; i++)
      println(df.format(Math.sqrt(i)));
   }

  public static void main(String[] args)
  {
    new FormatEx1();
  }
}
 

 

Beispiel 2: Werteausgabe in Tabellenform

// FormatEx2.java

import ch.aplu.util.*;
import java.text.*;

public class FormatEx2 extends Console
{
  FormatEx2()
  {
    DecimalFormat df = new DecimalFormat("#0.000")// Anz. Dezimalstellen
    print("i:");
    for (int i = 0; i < 5; i++)
      print("\t" + i);                              // "\t" Tabulator

    print("\nf(i):");                               // "\n" Zeilenschaltung
    for (int i = 0; i < 5; i++)
      print("\t" + df.format(Math.sqrt(i)));
  }

  public static void main(String[] args)
  {
        new FormatEx2();
  }
}
 

 

Beispiel 3: Formatierte Ausgabe in zwei Spalten

// FormatEx3.java

import ch.aplu.util.*;
import java.text.*;

class FormatEx3 extends Console
{
  FormatEx3()
  {
    DecimalFormat df1 = new DecimalFormat("#0");
    DecimalFormat df2 = new DecimalFormat("#0.000");

    for (int x = 0; x < 120; x = x + 2)
    {
      double y = Math.sqrt(x)// Funktion
      println("  x =" + pad(df1.format(x)4) + "\t"+
              "  y =" + pad(df2.format(y)7));
    }
  }

  public static void main(String[] args)
  {
    new FormatEx3();
  }
}
 

 

Beispiel 4: Berechnet die Nullstellen der Funktion y = sqrt(x) - cos(x)

// FormatEx4.java
// Berechnet Nullstellen der Funktion y = sqrt(x) - cos(x)

import java.text.*;
import ch.aplu.util.*;

public class FormatEx4 extends Console
{
  public FormatEx4()
  {
    String pattern = "#0.00000000";
    DecimalFormat df = new DecimalFormat(pattern);
    final double toleranz = 0.1E-7;
    double a = 0;
    double b = Math.PI/2;
    double x;
    double y;

    while(- a > toleranz)
    {
      x = (+ b)/2;
      y = Math.sqrt(x) - Math.cos(x);
      print("  a = ");
      print(df.format(a) + "     b = ");
      println(df.format(b));
      if (< 0)
        a = x;
      else
        b = x;
      y = Math.sqrt(x) - Math.cos(x);
    }

    x = (+ b)/2;
    y = Math.sqrt(x) - Math.cos(x);
    println("\nsqrt(x) =  " + df.format(Math.sqrt(x)));
    println("cos(x)  =  " + df.format(Math.cos(x)));
    println("\n  x   =  " + df.format(x));
    println("  y   =  " + df.format(y));
  }


  public static void main(String[] args)
  {
    new FormatEx4();
  }
}