public class Test
{ public static void main (String args[])
{ double r=4.5;
double u=Math.PI*r;
System.out.println("Der Umfang eines Kreises mit Radius "+r+" ist "+u);
}
}
Das Ergebnis -727379968 wegen eines int-Überlaufs.
Das Ergebnis ist -1.1102230246251565E-16, weil 0.1 imBinärsystem nicht exakt darstellbar ist. Ein Testprogramm ist etwa
System.out.println(0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1-1.0);
public class Test
{ public static void main (String args[])
{ double e=Math.exp(1.0);
int n=10;
double r=Math.pow(1+1.0/n,n);
System.out.println(r+", "+(e-r));
n=100;
r=Math.pow(1+1.0/n,n);
System.out.println(r+", "+(e-r));
n=1000;
r=Math.pow(1+1.0/n,n);
System.out.println(r+", "+(e-r));
n=10000;
r=Math.pow(1+1.0/n,n);
System.out.println(r+", "+(e-r));
}
}
Die Ausgabe ist
2.5937424601000023, 0.12453936835904278 2.7048138294215285, 0.01346799903751661 2.7169239322355936, 0.0013578962234515046 2.7181459268249255, 1.35901634119584E-4
Man beachte Also genügt n=1000.
System.out.println((char)27);
(x>=1) && (x<=2)
Das Ergebnis ist NaN (Not a Number).
public class Test
{ public static void main (String args[])
{ double sum=0;
for (int i=1; i<100; i++) sum+=i*i;
System.out.println(sum);
}
}
public class Test
{ public static void main (String args[])
{ int n=27;
while (n!=1)
{ System.out.println(n);
if (n%2==0) n=n/2;
else n=3*n+1;
}
}
}
public class Test
{ public static void main (String args[])
{ int a=1,b=1;
for (int i=3; i<=20; i++)
{ int c=a+b;
System.out.println(c);
a=b; b=c;
}
}
}
public class Test
{ public static void main (String args[])
{ double x=0;
while (true)
{ System.out.println(x);
x=Math.cos(x);
}
}
}
public class Test
{ public static void main (String args[])
{ double x=0,old=x;
do
{ System.out.println(x);
old=x;
x=Math.cos(x);
} while (Math.abs(x-old)>1e-13);
}
}
Gegen welchen Wert konvergiert das wohl?
public class Test
{
static public void main (String args[])
{ int n=10000; // Anzahl der Zufallszahlen
double R[]=new double[n]; // erzeugt Platz fuer n Zahlen
// Zufallszahlen:
for (int i=0; i<n; i++) R[i]=Math.random();
// erzeuge Zufallszahlen
// Mittelwert:
double sum=0;
for (double x : R) sum+=x; // berechne Summe
double mean=sum/n;
System.out.println("Mittelwert : "+mean);
// Stichprobenabweichung:
sum=0;
for (double x : R) sum+=(mean-x)*(mean-x);
// berechne Varianz
System.out.println("Standard-Abweichung : "
+Math.sqrt(sum/(n-1)));
// Verteilung:
int m=10;
int I[]=new int[m]; // Platz fuer m Zaehler
for (int i=0; i<m; i++) I[i]=0; // mit 0 initialisieren
for (double x : R) // zaehlen
{ int j=(int)Math.floor(x*m);
// in welchem Intervall liegt R[i]?
if (j>=m) j=m-1; // falls R[i]==1.0
I[j]++; // erhoehe Zaehler
}
// Ausgabe:
for (int j=0; j<m; j++) // Ausgabe der Zaehlungen
System.out.println((j+1)+" : "+I[j]);
}
}
public class Test
{ public static void main (String args[])
{ int n=1000;
double R[]=new double[n];
int i;
for (i=0; i<n; i++) R[i]=Math.random();
double max=R[0];
for (i=1; i<n; i++)
if (R[i]>max) max=R[i];
System.out.println(max);
}
}
public class Test
{ public static void main (String args[])
{ int i,n=1000;
double max=Math.random();
for (i=1; i<n; i++)
{ double h=Math.random();
if (h>max) max=h;
}
System.out.println(max);
}
}
public class Test
{ public static void main (String args[])
{ int i,n=1000;
double R[]=new double[1000];
for (i=0; i<n; i++) R[i]=Math.random();
double max1,max2;
if (R[0]>R[1])
{ max1=R[0]; max2=R[1];
}
else
{ max2=R[0]; max1=R[1];
}
for (i=2; i<n; i++)
{ if (R[i]>max1)
{ max2=max1; max1=R[i];
}
else if (R[i]>max2) max2=R[i];
}
System.out.println(max1);
System.out.println(max2);
}
}
Bei dieser Aufgabe muß man darauf achten, von hinten nach vorne zu rechnen, da sonst das noch Benötigte überschrieben wird.
public class Test
{ public static void main (String args[])
{ int n=20;
int p[]=new int[n];
p[0]=1;
int i,j;
for (i=1; i<n; i++)
{ for (j=0; j<i; j++) System.out.print(p[j]+" ");
System.out.println();
p[i]=1;
for (j=i-1; j>=1; j--) p[j]=p[j]+p[j-1];
p[0]=1;
}
}
}
public class Test
{ public static void main (String args[])
{ int i,n=100;
double y[]=new double[n+1];
for (i=0; i<=n; i++) y[i]=Math.cos(i*0.01);
double sum=0;
for (i=0; i<=n; i++) sum+=y[i];
System.out.println(sum*0.01);
sum=y[0]+4*y[1]+y[n];
for (i=2; i<n; i+=2) sum+=2*y[i]+4*y[i+1];
System.out.println(sum*0.01/3);
System.out.println(Math.sin(1));
}
}
public class Test
{ static public void main (String args[])
{ System.out.println(cosh(1.5));
}
static double sinh (double x)
{ return (Math.exp(x)-Math.exp(-x))/2;
}
static double cosh (double x)
{ return (Math.exp(x)+Math.exp(-x))/2;
}
}
public class Test
{ static public void main (String args[])
{ double R[]=new double[1000];
for (int i=0; i<R.length; i++) R[i]=Math.random();
System.out.println(max(R));
}
static double max (double x[])
{ double m=x[0];
for (int i=1; i<x.length; i++)
if (m<x[1]) m=x[1];
return m;
}
}
public class Test
{ static public void main (String args[])
{ System.out.println((int)choose(49,6));
}
static double fak (int n)
{ double r=1;
for (int i=2; i<=n; i++) r*=i;
return r;
}
static double choose (int n, int k)
{ return fak(n)/(fak(k)*fak(n-k));
}
}
public class Test
{ static public void main (String args[])
{ System.out.println((int)choose(49,6));
}
static double choose (int n, int k)
{ if (k>n/2) k=n-k;
double r=1;
for (int i=1; i<=k; i++) r*=(n-i+1)/(double)i;
return r;
}
}
public class Test
{ static public void main (String args[])
{ System.out.println(pow(2,10));
}
static double pow (double x, int n)
{ if (n==0) return 1;
else if (n%2==0) return sqr(pow(x,n/2));
else return x*sqr(pow(x,n/2));
}
static double sqr (double x)
{ return x*x;
}
}
public class Test
{ static public void main (String args[])
{ System.out.println(ggt(52,273));
}
static int ggt (int n, int m)
{ if (m==1 || n==1) return 1;
else
{ int r=n%m;
if (r!=0) return ggt(m,r);
else return m;
}
}
}
class Koord
{ private double X,Y;
public Koord (double x, double y)
{ X=x; Y=y;
}
public double x ()
{ return X;
}
public double y ()
{ return Y;
}
public void set (double x, double y)
{ X=x; Y=y;
}
}
class Punkt extends Koord
{ public Punkt (double x, double y)
{ super(x,y);
}
}
class Kreis extends Koord
{ private double R;
public Kreis (double x, double y, double r)
{ super(x,y);
R=r;
}
double r () { return R; }
void set (double x, double y, double r)
{ super.set(x,y);
R=r;
}
}
public class Test
{ static public void main (String args[])
{ Kreis k=new Kreis(0.5,0.5,0.5);
int count=0,n=1000000;
for (int i=0; i<n; i++)
{ Punkt p=new Punkt(Math.random(),Math.random());
if (contains(k,p)) count++;
}
System.out.println((double)count/n);
System.out.println(Math.PI/4);
}
static boolean contains (Kreis k, Punkt p)
{ if (Math.sqrt(sqr(k.x()-p.x())+sqr(k.y()-p.y()))<k.r()) return true;
else return false;
}
static double sqr (double x)
{ return x*x;
}
}
public class Test
{ public static void main (String args[])
{ int n=1000000;
BitSet b=new BitSet(n+1);
int i,j;
for (i=0; i<=n; i++) b.set(i);
for (i=2; i<n; i++)
{ if (b.get(i))
for (j=2*i; j<=n; j+=i) b.clear(j);
}
int count=0;
for (i=2; i<n; i++)
if (b.get(i)) count++;
System.out.println(count);
}
}
import java.util.BitSet;
public class Test
{ public static void main (String args[])
{ int n=1000000;
BitSet b=new BitSet(n/2);
int i,j,k;
for (k=0; k<=n/2; k++) b.set(k);
double max=Math.sqrt(n);
for (k=0,i=3; i<n && k<max; i+=2,k++)
{ if (b.get(k))
for (j=k+i; j<n/2; j+=i) b.clear(j);
}
int count=0;
for (k=0; k<n/2; k++)
if (b.get(k)) count++;
System.out.println(count+1);
}
}
Man beachte, daß nun Bit k für die Zahl 2k+1 steht.
public class Test
{ public static void main (String args[])
{ System.out.println(isPalindrom(args[0]));
}
public static boolean isPalindrom (String s)
{ int i=0,n=s.length()-1;
while (i<n)
{ if (s.charAt(i)!=s.charAt(n)) return false;
i++; n--;
}
return true;
}
}
public class Test
{ public static void main (String args[])
{ System.out.println(simplify(args[0]));
}
public static String simplify (String s)
{ StringBuffer b=new StringBuffer();
for (int i=0; i<s.length(); i++)
{ char c=s.charAt(i);
b.append(c);
while (i<s.length()-1 && c==s.charAt(i+1)) i++;
}
return b.toString();
}
}
import java.util.*;
public class Test
{
static public void main (String args[])
{ int n=1000;
// Array einrichten:
ArrayList<Double> L = new ArrayList<Double>();
for (int i=0; i<n; i++) L.add(Math.random());
// Mittelwert berechnen:
double sum=0;
for (Double x : L) sum+=x.doubleValue();
System.out.println(sum/n);
// Alle x<0.5 entfernen:
Iterator<Double> x=L.iterator();
while (x.hasNext())
{ if (x.next().doubleValue()<0.5) x.remove();
}
// Größe ausgeben:
System.out.println(L.size());
}
}
public class Test
{ public static void main (String args[])
{ int n=1000;
LinkedList<Double> L=new LinkedList<Double>();
for (int i=0; i<1000; i++) L.add(Math.random());
// automatische Umwandlung!
ArrayList<Double> A=new ArrayList<Double>();
A.addAll(L);
System.out.println(A.size());
}
}
class TestCanvas extends Canvas
{ private int W,H;
public double Xmin=-10,Ymin=-2,Xmax=10,Ymax=2;
// Die Plotkoordinaten in der mathematischen Ebene
public void paint (Graphics g)
{ Dimension d=getSize();
W=d.width; H=d.height;
// Zeichne:
int c1=col(Xmin),r1=row(f(Xmin)),c2,r2;
// c1,c2 sind jeweils die alten Koordinaten
// (also die Anfangspunkte der Linien)
for (int i=0; i<W; i++)
{ double x=Xmin+(Xmax-Xmin)/W*i;
double y=f(x);
c2=col(x); r2=row(y);
g.drawLine(c1,r1,c2,r2);
c1=c2; r1=r2;
}
}
// Die Funktion, die geplottet wird:
double f (double x)
{ if (Math.abs(x)<1e-10) return 1.0;
else return Math.sin(x)/x;
}
// Umrechnung von x-Koordinate in Bildschirmspalte
private int col (double x)
{ return (int)((x-Xmin)/(Xmax-Xmin)*W);
}
// Umrechnung von y-Koordinate in Bildschirmzeile
private int row (double y)
{ return (int)((Ymax-y)/(Ymax-Ymin)*H);
// Man beachte die Umkehrung dieser Koordinate
}
}
import java.awt.*;
class TestCanvas extends Canvas
{ public void paint (Graphics g)
{ Dimension d=getSize();
int w=d.width,h=d.height;
Color C;
for (int i=0; i<w; i++)
{ float x=(float)i/w;
C=new Color(x,x,x);
g.setColor(C);
g.drawLine(i,0,i,h-1);
}
}
}
public class Test
{ public static void main (String args[])
{ Frame F=new Frame();
F.setSize(300,300);
F.add(new TestCanvas());
F.setVisible(true);
}
}
import java.awt.*;
class TestCanvas extends Canvas
{ public void paint (Graphics g)
{ Dimension d=getSize();
int w=d.width,h=d.height;
g.drawLine(0,0,w-1,h-1);
g.drawLine(0,h-1,w-1,0);
g.drawRect(0,0,w-1,h-1);
}
public Dimension getPreferredSize ()
{ return new Dimension(20,20);
}
}
public class Test
{ public static void main (String args[])
{ Frame F=new Frame();
F.setSize(300,300);
F.setLayout(new BorderLayout());
F.add("North",new TestCanvas());
F.add("East",new TestCanvas());
F.add("West",new TestCanvas());
F.add("South",new TestCanvas());
F.add("Center",new TestCanvas());
F.setVisible(true);
}
}
class StringList
{ protected StringElement First,Last;
public StringList ()
{ First=Last=null; // dasselbe wie First=null; Last=null;
}
public void prepend (String s)
{ StringElement n=new StringElement(s);
if (isEmpty()) First=Last=n;
else First=new StringElement(s,First);
}
public void append (String s)
{ StringElement n=new StringElement(s);
if (isEmpty()) First=n;
else (Last.setNext(n));
Last=n;
}
public boolean isEmpty ()
{ return First==null;
}
public StringElement getFirst ()
{ return First;
}
public Enumeration elements ()
{ Vector v=new Vector();
StringElement e=First;
while (e!=null)
{ v.addElement(e.getString());
e=(StringElement)e.getNext();
}
return v.elements();
}
}
import java.awt.*;
import java.awt.event.*;
class TestCanvas extends Canvas implements MouseListener
{ private int x=-100,y=-100;
public TestCanvas ()
{ addMouseListener(this);
}
public void paint (Graphics g)
{ g.drawRect(x-10,y-10,20,20);
}
public void mousePressed (MouseEvent e)
{ x=e.getX(); y=e.getY();
repaint();
}
public void mouseReleased (MouseEvent e) {}
public void mouseEntered (MouseEvent e) {}
public void mouseExited (MouseEvent e) {}
public void mouseClicked (MouseEvent e) {}
}
class TestFrame extends Frame
{ public TestFrame ()
{ super("Test Frame");
setSize(300,300);
add(new TestCanvas());
setVisible(true);
addWindowListener(
new WindowAdapter ()
{ public void windowClosing (WindowEvent e)
{ dispose(); System.exit(0);
}
}
);
}
}
public class Test
{ public static void main (String args[])
{ new TestFrame();
}
}
oder mit einem MouseAdapter
class TestCanvas extends Canvas
{ private int x=-100,y=-100;
public TestCanvas ()
{ addMouseListener(
new MouseAdapter ()
{ public void mousePressed (MouseEvent e)
{ x=e.getX(); y=e.getY();
repaint();
}
}
);
}
public void paint (Graphics g)
{ g.drawRect(x-10,y-10,20,20);
}
}
class TestCanvas extends Canvas
{ private int X=-100,Y=-100;
public void paint (Graphics g)
{ g.drawRect(X-10,Y-10,20,20);
}
public boolean mouseDown (Event e, int x, int y)
{ X=x; Y=y;
repaint();
return true;
}
}
import java.awt.*;
import java.awt.event.*;
class TestFrame extends Frame
{ public TestFrame ()
{ super("Test Frame");
setSize(300,300);
setVisible(true);
addKeyListener(
new KeyAdapter ()
{ public void keyPressed (KeyEvent e)
{ if (e.getKeyCode()==KeyEvent.VK_ESCAPE)
{ dispose(); System.exit(0);
}
}
}
);
}
}
public class Test
{ public static void main (String args[])
{ new TestFrame();
}
}
und ohne KeyAdapter
class TestFrame extends Frame implements KeyListener
{ public TestFrame ()
{ super("Test Frame");
setSize(300,300);
setVisible(true);
addKeyListener(this);
}
public void keyPressed (KeyEvent e)
{ if (e.getKeyCode()==KeyEvent.VK_ESCAPE)
{ dispose(); System.exit(0);
}
}
public void keyTyped (KeyEvent e) {}
public void keyReleased (KeyEvent e) {}
}
import java.awt.*;
import java.awt.event.*;
class TestCanvas extends Canvas
{ public TestCanvas ()
{ addKeyListener(
new KeyAdapter ()
{ public void keyPressed (KeyEvent e)
{ System.out.println("Canvas: "+e);
}
}
);
}
}
class TestFrame extends Frame
{ public TestFrame ()
{ super("Test Frame");
setSize(300,300);
add(new TestCanvas());
setVisible(true);
addKeyListener(
new KeyAdapter ()
{ public void keyPressed (KeyEvent e)
{ System.out.println("Frame. "+e);
}
}
);
}
}
public class Test
{ public static void main (String args[])
{ new TestFrame();
}
}
Es ist immer die Canvas, die den Focus hat. Wenn man zwei Canvas in den Frame setzt, so bleibt der Focus beim ersten.
Um zu erreichen, daß der Frame Tastatur-Ereignisse erhält, registriert man einfach das Fenster als Key-Listener des Canvas.
class TestFrame extends Frame
{ public TestFrame ()
{ super("Test Frame");
setSize(300,300);
Canvas c1=new TestCanvas();
add(c1);
setVisible(true);
c1.addKeyListener(
new KeyAdapter ()
{ public void keyPressed (KeyEvent e)
{ dispose(); System.exit(0);
}
}
);
}
}
class TestFrame extends Frame
{ public TestFrame ()
{ super("Test Frame");
setSize(300,300);
Canvas c1;
setLayout(new BorderLayout());
add("Center",c1=new TestCanvas());
add("South",new TextField());
setVisible(true);
c1.addKeyListener(
new KeyAdapter ()
{ public void keyPressed (KeyEvent e)
{ dispose(); System.exit(0);
}
}
);
}
}
Die Antwort heißt: Nein.
class TestCanvas extends Canvas
{ public TestCanvas ()
{ addKeyListener(
new KeyAdapter ()
{ public void keyPressed (KeyEvent e)
{ System.out.println("Canvas :"+e);
}
}
);
addMouseListener(
new MouseAdapter ()
{ public void mousePressed (MouseEvent e)
{ requestFocus();
}
}
);
}
}
Die Antwort heißt: Ja.
import java.awt.*;
import java.awt.event.*;
class PaintCanvas extends Canvas
{ Color C;
int X,Y;
public PaintCanvas ()
{ addMouseListener(
new MouseAdapter ()
{ public void mousePressed (MouseEvent e)
{ X=e.getX(); Y=e.getY();
}
}
);
addMouseMotionListener(
new MouseMotionAdapter ()
{ public void mouseDragged (MouseEvent e)
{ Graphics g=getGraphics();
g.setColor(C);
g.drawLine(X,Y,e.getX(),e.getY());
X=e.getX(); Y=e.getY();
g.dispose();
}
}
);
setBackground(Color.black);
}
public void setColor (Color c) { C=c; }
}
class TestFrame extends Frame
implements ItemListener
{ String strings[]={"white","blue","red","green","yellow","pink"};
Color colors[]={Color.white,Color.blue,Color.red,Color.green,
Color.yellow,Color.pink};
Choice choice;
PaintCanvas canvas;
public TestFrame ()
{ super("Test");
setLayout(new BorderLayout());
add("Center",canvas=new PaintCanvas());
canvas.setColor(colors[0]);
Panel p=new Panel();
p.add(choice=new Choice());
for (int i=0; i<strings.length; i++) choice.addItem(strings[i]);
choice.addItemListener(this);
choice.select(strings[0]);
add("South",p);
addWindowListener(
new WindowAdapter ()
{ public void windowClosing (WindowEvent e)
{ dispose(); System.exit(0);
}
}
);
setSize(400,400);
show();
}
public void itemStateChanged (ItemEvent e)
{ int i=choice.getSelectedIndex();
if (i>=0) canvas.setColor(colors[i]);
}
}
public class Test
{ public static void main (String args[])
{ new TestFrame();
}
}
import java.awt.*;
import java.awt.event.*;
class CloseQuestion extends Dialog
implements ActionListener
{ private boolean Yes=false;
public CloseQuestion (Frame f)
{ super(f,"Close",true);
add("North",new Label("Really close?"));
Panel p=new Panel();
Button b;
p.add(b=new Button("Yes")); b.addActionListener(this);
p.add(b=new Button("No")); b.addActionListener(this);
add("South",p);
pack();
setLocation(f.getLocation().x+100,f.getLocation().y+100);
show();
}
public void actionPerformed (ActionEvent e)
{ if (e.getActionCommand().equals("Yes"))
{ Yes=true;
}
dispose();
}
public boolean isYes ()
{ return Yes;
}
}
class TestFrame extends Frame
implements ActionListener
{ public TestFrame ()
{ // build up the menu bar
MenuBar m=new MenuBar();
setMenuBar(m);
Menu test=new Menu("Test"); // the menu
m.add(test);
MenuItem item=new MenuItem("Close"); // an item
item.addActionListener(this);
test.add(item);
addWindowListener(
new WindowAdapter ()
{ public void windowClosing (WindowEvent e)
{ close();
}
}
);
setSize(400,400);
show();
}
public void actionPerformed (ActionEvent e)
{ if (e.getActionCommand().equals("Close")) close();
}
public void close ()
{ if (new CloseQuestion(this).isYes())
{ dispose(); System.exit(0);
}
}
}
public class Test
{ public static void main (String args[])
{ new TestFrame();
}
}
...
interface ColorListener
{ public void setColor (Color c);
}
interface CloseListener
{ public void close ();
}
...
class ColorEdit extends Dialog
implements ActionListener
{ ...
Vector ColorL=new Vector(),CloseL=new Vector();
public ColorEdit (Frame F, Color c)
...
public void actionPerformed (ActionEvent e)
{ if (e.getActionCommand().equals("Cancel"))
{ C=Cold; tell();
}
Enumeration en=CloseL.elements();
while (en.hasMoreElements()) ((CloseListener)en.nextElement()).close();
dispose();
}
public void addCloseListener (CloseListener cl)
{ CloseL.addElement(cl);
}
public void removeCloseListener (CloseListener cl)
{ CloseL.removeElement(cl);
}
public void addColorListener (ColorListener cl)
{ ColorL.addElement(cl);
}
public void removeColorListener (ColorListener cl)
{ ColorL.removeElement(cl);
}
...
void tell ()
{ Enumeration e=ColorL.elements();
while (e.hasMoreElements())
{ ((ColorListener)e.nextElement()).setColor(C);
}
}
}
class TestFrame extends Frame
implements ColorListener,CloseListener
{ ...
public void coloredit ()
{ if (CE==null)
{ CE=new ColorEdit(this,C);
CE.addColorListener(this);
CE.addCloseListener(this);
}
}
...
}
...
import java.awt.*;
import java.applet.*;
import java.util.*;
public class DateApplet extends Applet
{ String s;
public void init ()
{ Date d=new Date();
s=d.toString();
}
public void paint (Graphics g)
{ g.drawString(s,50,50);
}
}
Es ist möglich, daß der Netscape Communicator die falsche Zeit anzeigt. In diesem Fall verwendet seine Java-Umgebung die falsche Zeitzone.
import java.awt.*;
import java.applet.*;
public class SinApplet extends Applet
{ double Xmin=-10,Xmax=10,Ymin=-2,Ymax=2;
int W,H;
public void paint (Graphics g)
{ Dimension d=size();
W=d.width; H=d.height;
// Zeichne Rahmen:
g.setColor(Color.black);
g.drawRect(0,0,W-1,H-1);
// Zeichne:
g.setColor(Color.green);
int c1=col(Xmin),r1=row(f(Xmin)),c2,r2;
// c1,c2 sind jeweils die alten Koordinaten
// (also die Anfangspunkte der Linien)
for (int i=0; i<W; i++)
{ double x=Xmin+(Xmax-Xmin)/W*i;
double y=f(x);
c2=col(x); r2=row(y);
g.drawLine(c1,r1,c2,r2);
c1=c2; r1=r2;
}
}
// Die Funktion, die geplottet wird:
double f (double x)
{ if (Math.abs(x)<1e-10) return 1.0;
else return Math.sin(x)/x;
}
// Umrechnung von x-Koordinate in Bildschirmspalte
private int col (double x)
{ return (int)((x-Xmin)/(Xmax-Xmin)*W);
}
// Umrechnung von y-Koordinate in Bildschirmzeile
private int row (double y)
{ return (int)((Ymax-y)/(Ymax-Ymin)*H);
// Man beachte die Umkehrung dieser Koordinate
}
}
import java.awt.*;
import java.applet.*;
public class DateApplet extends Applet
{ public boolean keyDown (Event e, int key)
{ System.out.println("hi");
showStatus("Key "+key);
return true;
}
}
Die Konsolenausgabe "hi" sollte im Falle des Applet-Viewer im Kommandofenster sichtbar sein. Im Browser läßt sich eine Java-Konsole öffnen. Allerdings nimmt nur der Browser Tastaturereignisse tatsächlich an, und erst dann, wenn man in das Applet klickt.
import java.awt.*;
import java.applet.*;
import java.awt.image.*;
public class BallApplet extends Applet implements Runnable
{ Thread A;
boolean Stop;
Image I; // Puffer
Image Back; // Hintergrund
Image Ball; // Ball
Graphics G; // Graphics fuer den Puffer
int N=4; // Anzahl der Bälle
int X[],Y[],DX[],DY[],SY[]; // Ballkoordinaten von links unten gesehen
int W,H; // Hoehe und Weite des Applets
final int S=20; // Kugelgroesse als Konstante
public void init ()
{ W=size().width; H=size().height;
// Bestimme Hoehe und Weite
I=createImage(W,H); // Erzeuge Puffer
G=I.getGraphics();
Back=getImage(getCodeBase(),"ziegel.gif");
MediaTracker T=new MediaTracker(this);
T.addImage(Back,0);
try
{ T.waitForAll();
}
catch (InterruptedException e) {}
Ball=createBall(S);
X=new int[N]; Y=new int[N]; DX=new int[N]; DY=new int[N]; SY=new int[N];
paintBall(G);
}
Image createBall (int S)
// Ein gerenderter Ball mit Radius S
{ int i,j,k;
int P[]=new int[4*(S+1)*(S+1)]; // fuer die Pixel
k=0;
double red,green,blue,light,x,y,z;
for (i=-S; i<=S; i++)
for (j=-S; j<=S; j++)
{ // Berechne x,y,z-Koordinate auf der Balloberflaeche
x=-(double)i/S;
y=(double)j/S;
z=1-x*x-y*y;
if (z<=0) P[k]=0; // außerhalb des Balls!
else
{ z=Math.sqrt(z);
light=(x+y+z)/Math.sqrt(3)*0.4;
// Vectorprodukt mit 1,1,1
red=0.6*(1+light); // Rotanteil
green=0.2*(1+light); // Gruenanteil
blue=0; // Blauanteil
P[k]=255<<24| // nicht transparent!
(int)(red*255)<<16|
(int)(green*255)<<8|
(int)(blue*255);
// P[k] setzt sich in vier Bytes aus den
// Farben und der Transparenz zusammen
}
k++;
}
return createImage( // Erzeuge das Image
new MemoryImageSource(2*S+1,2*S+1,ColorModel.getRGBdefault(),
P,0,2*S+1));
}
public void paintBall (Graphics g)
// Hintergrund und Kugel neu Zeichnen
{ g.drawImage(Back,0,0,this);
for (int i=0; i<N; i++)
g.drawImage(Ball,X[i]-S,H-Y[i]-S,this);
}
public void paint (Graphics g)
// Kopiere einfach das Image auf den Schirm
{ g.drawImage(I,0,0,this);
}
public void update (Graphics g)
// Hintergrund wird selbst neu gezeichnet
// normalerweise erledigt dies update()
{ paint(g);
}
public void start ()
// Kugel startet in der Mitte unten
{ for (int i=0; i<N; i++)
{ X[i]=(int)(2*S+Math.random()*(W-4*S));
Y[i]=S;
if (Math.random()>0.5) DX[i]=1;
else DX[i]=-1;
SY[i]=DY[i]=5+(int)(Math.random()*10);
}
A=new Thread(this);
A.start();
Stop=false;
}
public void stop ()
// Stoppe Thread
{ Stop=true;
}
public void run ()
// Die Schleife
{ while (!Stop)
{ // Ball verschieben:
for (int i=0; i<N; i++)
{ if (X[i]+DX[i]<S) DX[i]=-DX[i];
if (X[i]>W-S-1) DX[i]=-DX[i];
if (Y[i]+DY[i]<S) { DY[i]=SY[i]; }
X[i]+=DX[i]; Y[i]+=DY[i]; DY[i]--;
}
// Ball neu zeichnen und auf Schirm kopieren
paintBall(G);
Graphics g=getGraphics();
paint(g);
g.dispose();
// Etwas verzögern
try { A.sleep(50); } catch (Exception e) {}
}
}
}
import java.applet.*;
import java.util.*;
public class ClockApplet extends Applet implements Runnable
{ Thread A;
boolean Stop;
public void paint (Graphics g)
{ Date d=new Date();
String s=format(d.getHours())+":"+
format(d.getMinutes())+":"+format(d.getSeconds());
g.drawString(s,50,50);
}
public String format (int n)
{ if (n<10) return "0"+n;
else return ""+n;
}
public void start ()
{ A=new Thread(this);
A.start();
Stop=false;
}
public void stop ()
{ Stop=true;
}
public void run ()
{ while (!Stop)
{ try
{ A.sleep(1000);
}
catch (Exception ex) {}
repaint();
}
}
}
import java.awt.*;
import java.applet.*;
import java.util.*;
public class ClockApplet extends Applet implements Runnable
{ Thread A;
boolean Stop;
int W,H;
public void paint (Graphics g)
{ Date d=new Date();
g.drawOval(0,0,W-1,H-1);
hand(g,(d.getHours()/12.0+d.getMinutes()/720.0),0.6,Color.blue.darker());
hand(g,d.getMinutes()/60.0,0.8,Color.blue.darker());
hand(g,d.getSeconds()/60.0,0.75,Color.green.darker());
}
public void hand (Graphics g, double w, double l, Color c)
{ g.setColor(c);
double x1,y1,x2,y2;
w=Math.PI/2-2*w*Math.PI;
x1=-Math.cos(2)*0.1; y1=-Math.sin(w)*0.1;
x2=Math.cos(w)*l; y2=Math.sin(w)*l;
g.drawLine(col(x1),row(y1),col(x2),row(y2));
}
public int col (double x)
{ return (int)(x*W/2+W/2);
}
public int row (double y)
{ return H-(int)(y*H/2+H/2);
}
public void init ()
{ W=size().width; H=size().height;
}
public void start ()
{ A=new Thread(this);
A.start();
Stop=false;
}
public void stop ()
{ Stop=true;
}
public void run ()
{ while (!Stop)
{ try
{ A.sleep(1000);
}
catch (Exception ex) {}
repaint();
}
}
}
public class Test implements Runnable
{ int n=0;
public static void main (String args[])
{ Test t=new Test();
new Thread(t).start();
new Thread(t).start();
}
public void run ()
{ while (n<40)
{ System.out.println(n);
n=n+1;
}
}
}
import java.awt.*;
import java.applet.*;
public class TestApplet extends Applet implements Runnable
{ String S;
int pos;
Thread T;
Image I;
Graphics G;
int W,H,Base,StringW;
public void init ()
{ S=getParameter("String");
if (S==null) S="High!";
W=size().width;
H=size().height;
I=createImage(W,H);
G=I.getGraphics();
G.setFont(new Font("Courier",Font.BOLD,H*2/3));
FontMetrics fm=G.getFontMetrics();
Base=(H-fm.getHeight())/2+fm.getAscent();
StringW=fm.stringWidth(S);
pos=10000;
T=new Thread(this);
T.start();
T.suspend();
}
public void run ()
{ while (true)
{ pos++;
updateImage();
Graphics g=getGraphics();
paint(g);
g.dispose();
try { T.sleep(10); } catch (Exception e) {}
}
}
public void start ()
{ T.resume();
}
public void stop ()
{ T.suspend();
}
public void updateImage ()
{ G.setColor(Color.green.darker());
G.fillRect(0,0,W,H);
if (pos>W) pos=-StringW;
G.setColor(Color.white);
G.drawString(S,pos,Base);
G.setColor(Color.blue.darker());
G.drawRect(0,0,W-1,H-1);
}
public void paint (Graphics g)
{ g.drawImage(I,0,0,this);
}
}
import java.io.*;
public class Test
{ public static void main (String args[])
{ try
{ InputStream is=new FileInputStream(args[0]);
BufferedReader in=new BufferedReader(
new InputStreamReader(is));
OutputStream os=new FileOutputStream(args[1]);
PrintWriter out=new PrintWriter(
new OutputStreamWriter(os,"Cp850"));
while (true)
{ String s=in.readLine();
if (s==null) break;
out.print(s);
out.write(13); out.write(10);
}
in.close();
out.close();
}
catch (Exception e)
{ System.out.println(e);
}
}
}
import java.io.*;
public class Test
{ public static void main (String args[])
{ if (args.length!=1) return;
long count=0;
File file=new File(args[0]);
if (file.exists())
{ if (file.isDirectory()) count+=addcount(file);
else count=file.length();
}
System.out.println(count);
}
public static long addcount (File dir)
{ String list[]=dir.list();
long count=0;
for (int i=0; i<list.length; i++)
{ File file=new File(dir,list[i]);
if (file.isDirectory()) count+=addcount(file);
else count+=file.length();
}
return count;
}
}
import java.io.*;
public class Test
{ public static void main (String args[])
{ if (args.length!=2) return;
long count=0;
File file=new File(args[0]);
if (file.exists())
{ if (file.isDirectory()) count+=addcount(file,args[1]);
else if (file.getName().endsWith(args[1])) count=file.length();
}
System.out.println(count);
}
public static long addcount (File dir, String ext)
{ String list[]=dir.list();
long count=0;
for (int i=0; i<list.length; i++)
{ File file=new File(dir,list[i]);
if (file.isDirectory()) count+=addcount(file,ext);
else if (file.getName().endsWith(ext)) count+=file.length();
}
return count;
}
}
import java.io.*;
public class Test
{ public static void main (String args[])
{ if (args.length!=3) return;
File file=new File(args[0]);
if (file.exists())
{ if (file.isDirectory()) grep(file,args[1],args[2]);
else if (file.getName().endsWith(args[1])) grep(file.getName(),args[2]);
}
}
public static void grep (File dir, String ext, String s)
{ String list[]=dir.list();
for (int i=0; i<list.length; i++)
{ File file=new File(dir,list[i]);
if (file.isDirectory()) grep(file,ext,s);
else if (file.getName().endsWith(ext)) grep(file.getName(),s);
}
}
public static void grep (String filename, String s)
{ try
{ BufferedReader in=new BufferedReader(
new InputStreamReader(
new FileInputStream(filename)));
String line;
while (true)
{ line=in.readLine();
if (line==null) break;
if (line.indexOf(s)>=0)
{ System.out.println(filename);
break;
}
}
in.close();
}
catch (Exception e) {}
}
}
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class client implements Runnable, ActionListener
{ PrintWriter Out;
BufferedReader In;
TextArea Output;
TextField Input;
DataInputStream data;
Frame F;
public client (Socket socket)
{ try
{ Out=new PrintWriter(
new DataOutputStream(socket.getOutputStream()),true);
In=new BufferedReader(new InputStreamReader(
data=new DataInputStream(socket.getInputStream())));
Frame f=new Frame("Client");
f.setSize(500,500);
f.setLayout(new BorderLayout());
f.add("Center",Output=new TextArea());
Output.setEditable(false);
f.add("South",Input=new TextField());
Input.addActionListener(this);
f.setVisible(true);
F=f;
f.addWindowListener(new WindowAdapter ()
{ public void windowClosing (WindowEvent e)
{ F.setVisible(false); F.dispose(); System.exit(0);
}
}
);
}
catch (Exception e)
{ System.err.println(e);
}
Thread t=new Thread(this);
t.start();
}
public static void main (String args[])
{ try
{ Socket socket=new Socket(args[0],Integer.parseInt(args[1]));
new client(socket);
}
catch (Exception e)
{ System.err.println(e);
}
}
public void run ()
{ try
{ StringBuffer s=new StringBuffer();
while (true)
{ s.setLength(0);
s.append((char)data.read());
while (data.available()>0)
{ s.append((char)data.read());
}
if (s.length()>0) Output.append(s.toString());
}
}
catch (Exception e)
{ Output.append("\n"+e);
}
}
public void actionPerformed (ActionEvent e)
{ if (e.getSource()==Input)
{ Out.println(Input.getText());
Input.setText("");
}
}
}
...
BufferedReader in=new BufferedReader(new InputStreamReader(
getClass().getResourceAsStream("/"+subject+"_"+Local.getDefault()+".txt")));
...
import java.util.*;
import java.text.*;
public class Test
{ public static void main (String args[])
{ GregorianCalendar C=new GregorianCalendar();
C.setTime(new Date());
System.out.println(DateFormat.getDateInstance(DateFormat.SHORT).format(
C.getTime()));
System.out.println("Current weekday: "+C.get(GregorianCalendar.DAY_OF_WEEK));
int n=0,m=0;
try
{ n=Integer.parseInt(args[0]);
m=Integer.parseInt(args[1]);
if (n>=m) throw new Exception("");
}
catch (Exception e)
{ System.err.println("Two years expected!");
System.exit(0);
}
int count[]=new int[7];
int i;
for (i=0; i<7; i++) count[i]=0;
for (i=n; i<=m; i++)
{ for (int j=1; j<12; j++)
{ C.set(i,j,13);
int d=C.get(Calendar.DAY_OF_WEEK);
count[d-1]++;
}
}
for (i=0; i<7; i++)
{ System.out.println(count[i]);
}
}
}
import java.io.*;
class StringNode implements Serializable
{ private String S;
protected StringNode Left,Right;
public StringNode (String s)
{ Left=Right=null;
S=s;
}
public void insert (String s) // Fuege s korrekt ein.
{ if (s.compareTo(S)>0) // dann rechts
{ if (Right==null) Right=new StringNode(s);
else Right.insert(s);
}
else // sonst links
{ if (Left==null) Left=new StringNode(s);
else Left.insert(s);
}
}
public String getString ()
{ return S;
}
public StringNode getLeft ()
{ return Left;
}
public StringNode getRight ()
{ return Right;
}
}
public class Test
{ public static void main (String args[])
{ StringNode tree=null;
for (int i=0; i<20; i++) // 20 Zusfallsstrings speichern
{ String s="Zufallszahl "+Math.random();
if (tree==null) tree=new StringNode(s);
else tree.insert(s);
}
try
{ // Schreibe Array auf Datei:
ObjectOutputStream out=
new ObjectOutputStream(new FileOutputStream("test.dat"));
out.writeObject(tree);
out.close();
// Lies Array ein:
ObjectInputStream in=
new ObjectInputStream(new FileInputStream("test.dat"));
tree=(StringNode)in.readObject();
in.close();
}
catch (Exception e) {}
print(tree); // Sortiert wieder ausdrucken
}
public static void print (StringNode tree)
// Rekursive Druckfunktion
{ if (tree==null) return;
print(tree.getLeft());
System.out.println(tree.getString());
print(tree.getRight());
}
}