©1994-2003 Kevin Boone
Home     Section index     K-Zone home Simple Java programs

Site search

Glossary
Confused by computer jargon? Look it up!

Shameless plug


Now available!

Articles
- Ten-minute guide to setting up a WAP site

- Talk like your boss: new developments in managerese

More...

Development
File handling in the Linux kernel

Java development for the Sony-Ericsson P800

SunONE Application Server 7 FAQ

More...

Linux
Using Linux with the Treo 600

- Linux on the Tecra M1

- Some notes on openzaurus

More...

Download
Java stuff

Linux stuff

More...

(Please read the download policy)

Home automation
The X10 system

Linux TW723 driver

More...

The K-Zone
K-Zone computing

K-Zone law

K-Zone education and science

K-Zone motorcycles

K-Zone DIY

K-Zone railways

K-Zone martial arts

About the author

K-Zone home page

 
Software development
Computing
Hello1.java
Add1.java
Add1_1.java
AwtTest.java
Button1.java
Button2.java
Calculator.java
CalculatorApp.java
ClockApplet.java
CountSpace1.java
DateTime.java
DoNothing.java
Factorial1.java
Factorial2.java
FontChooser.java
IfTest.java
Inheritance1.java
Loan.java
DiceThrower.java
MultiplicationTable.java
Queue.java
Reverse1.java
SoundApplet.java
Stressometer.java
TextReaderTest.java
WebMerge.java
Zener.java
`Div1' example program: demonstrates how to avoid the pitfall of integer division

Div1.java

// Div1.java
// A program that works out 2/5.  
// Kevin Boone, May 1999

import java.applet.Applet;
import java.awt.*;

public class Div1 extends Applet
{
public void paint (Graphics g)
	{
	// Note that not only must the result be stored in a 
	//  variable of type ``double'', (or ``float'', but not
	//  ``int'', the numbers have to be given as 2.0 and
	//  5.0, not 2 and 5. The problem is that the computer only
	//  does one thing at a time. If I say `2/5', it does the
	//  division using whole numbers (integers), then puts the
	//  result into the variable `result'. But by then it is too	
	//  late: the decimal part has already been lost. By saying
	//  2.0 and not 2, the Java compiler knows that it has to 
	//  do the calculation using the decimal part as well!

	double result = 2.0 / 5.0; 
	
	g.drawString ("2 / 5", 20, 20);

	g.drawString (Double.toString(result), 20, 40);
	}
}