Adjusting Values

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
Historical topic: Java appletsModern web browsers do not run Java applets. The Applet API was deprecated for removal before Java 25 and was removed in Java 26. Treat applet examples on this page as historical object-oriented/GUI examples; for new desktop interfaces use Swing where appropriate or JavaFX/OpenJFX.
go to previous page   go to home page   go to next page

Answer:

The problem is that sin(x) has values from -1.0 up to 1.0. When these are changed to int type in the statement

int startY = (int)Math.sin( x );

they will almost always be zero.

Adjusting Values

To use the drawLine() method, the endpoints of the line need to be positive integers. But what we want to graph consists of negative and positive numbers smaller than one!

To deal with this problem you need to scale the computed values into graphics coordinates. Say that the applet is 600 pixels wide, and that this is supposed to represent the range of 0.0 to 2*PI. So we have:

actual x valueinteger X to fit applet width
0.0 0
2*PI 599

The floating point number x can be changed into the correct integer X by using a linear equation:

X = x * 599/(2*PI)

This may look awful, but it is just algebra.

QUESTION 10:

Err... just algebra.... sure... Maybe we better check if it works. Fill in the following table by computing X by using the formula.

actual x valueX = x * 599/(2*PI)
0.0  
2*PI