Follow the instructions below. If you have questions along the way, ask. If you want to try something, go ahead. Whenever there are questions in the lab, answer them to your own satisfaction--you do not need to hand in your answers.
The only thing you need to hand in is in section IV below.
Goal: To get a simple program compiled and running.
/*
The traditional first program.
*/
class HelloWorld
{
public static void main( String[] args )
{
System.out.println( "Hello, world." );
}
}
What do "/*" and "*/" do?
Change the first appearance of the word "println" to "print". What happens?
import javax.swing.*;
class HelloWorldJ
{
public static void main( String[] args )
{
String myMessage;
myMessage = new String("Hello, world.");
JOptionPane.showMessageDialog(null,myMessage);
System.exit(0);
}
}
Goal: To see how basic arithmetic operations behave, and, as an added bonus, to see how to accept input from the person using the program.
Create a new class called "Arithmetic". Copy and paste the code from Arithmetic.java into an nedit window.
Compile and run the program. Enter integers when the program asks you to. What does the operation "%" do? How about "/"? (Try running the program several times with different input.)
Now change the type of a and b from "int" to "double", and change the two "Integer.parseInt" methods to "Double.parseDouble". Recompile. How does the behavior of "%" change? Get rid of the "%" line and recompile.
Your a and b variables now have type double. When you run the program, how is the behavior of "/" different from when a and b had type int? The type "double" is badly named--what does it mean in this context?
Notice the section at the top bracketed by /*...*/. This is a comment, as is anything following //. Suppose you want to "comment out" a block of code that's bugging you. That is, you want to make the compiler ignore some code without actually removing the code from your file. The /*...*/ style comments give you a convenient tool for doing this. Try commenting out everything in main. Recompile. What happens, and why? How can you fix the problem? Which style of comments is appropriate for documentation in your code, and which style of comments is appropriate for commenting out several lines of code at once?
Create a class called "Temperature" with a main method that asks for a temperature in Celsius and prints out the temperature in Fahrenheit. Use JOptionPane.showInputDialog for input and JOptionPane.showMessageDialog for output. The formula to convert Celsius to the equivalent Fahrenheit is:
fahrenheit = 1.8 x celsius + 32
Put the names of all students who worked on your Temperature class in the comment at the top of your source file. Then, submit the program electronically. To find out how to do so, go to submitting programs.