Datanom Basisfag

Programeksempler og vejledende løsninger til Java Gently kapitel 2:

Oprettet 11. april 1999

Kapitel 2 - eksempel 1 - Welcome

class Welcome

{

public static void main (String [] args)

{

System.out.println("Welcome to Java!");

}

}

Kapitel 2 - eksempel 2 - Olympic Rings

import java.awt.*;

import java.awt.event.*;

class Rings extends Frame

{

public Rings()

{

setTitle("Olympic Rings");

}

public static void main (String [] args)

{

Frame f = new Rings();

f.addWindowListener(new WindowAdapter()

{

public void windowClosing(WindowEvent e)

{

System.exit(0);

}

} );

f.setSize(300, 200);

f.setVisible(true);

}

public void paint (Graphics g)

{

g.setColor(Color.red);

g.drawOval(90,80,30,30);

g.setColor(Color.blue);

g.drawOval(115,80,30,30);

g.setColor(Color.green);

g.drawOval(140,80,30,30);

g.setColor(Color.yellow);

g.drawOval(165,80,30,30);

g.setColor(Color.black);

g.drawOval(195,80,30,30);

g.drawString("Olympic Rings", 120,40);

}

}

Kapitel 2 - Opgave 1 - Snowman

import java.awt.*;

import java.awt.event.*;

class Snowman extends Frame

{

public Snowman()

{

setTitle("Singing snowman");

}

public static void main (String [] args)

{

Frame f = new Snowman();

f.addWindowListener(new WindowAdapter()

{

public void windowClosing(WindowEvent e)

{

System.exit(0);

}

} );

f.setSize(300, 300);

f.setVisible(true);

}

public void paint (Graphics g)

{

g.setColor(Color.black);

g.drawOval(100,100,100,100); // Krop

g.drawOval(145,125,10,10); // Knapper

g.drawOval(145,150,10,10);

g.drawOval(145,175,10,10);

g.drawOval(125,50,50,50); // Hoved

g.drawOval(140,90,20,5); // Mund

g.drawOval(140,70,5,5); // Øjne

g.drawOval(160,70,5,5);

g.drawOval(88,100,25,25); // Arme

g.drawOval(187,100,25,25);

g.fillOval(125,50,50,10); // Hat

g.fillOval(130,45,30,10);

}

}

Kapitel 2 - Opgave 3 - Average

class Average

{

static final int weight1 = 20;

static final int weight2 = 30;

static final int weight3 = 50;

static final int mark1 = 8;

static final int mark2 = 6;

static final int mark3 = 11;

public static void main (String [] args)

{

double weightedAverage;

weightedAverage = (mark1 * weight1 + mark2 * weight2 +

mark3 * weight3) / 100.0;

System.out.println(weightedAverage);

}

}

Kapitel 2 - Opgave 4 - Fuel

class Fuel

{

static final double fuelConsumption = 8.0; // per 100 km

static final double tankCapacity = 40.0;

public static void main (String [] args)

{

System.out.print("Normal road: ");

System.out.print(tankCapacity / fuelConsumption * 100);

System.out.println(" km");

double fuelRough = fuelConsumption + fuelConsumption * 0.15;

System.out.print("Rough road: ");

System.out.print(tankCapacity / fuelRough * 100);

System.out.println(" km");

}

}