Sunteți pe pagina 1din 19

Java Lab 0: Hello World

1. Navigate to the c:\java folder on your computer and create a folder to store the
work you will do in this class. The name of the folder should have no spaces and include
part of your name or a nickname, so you will recognize it as yours in future classes.

2. Go to Start Menu->Programs->Accessories and click on Notepad. This opens up


Notepad which is the editor we’ll be using to write your source code for now. Type this
code below into Notepad:

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

3. Save the file as HelloWorld.java in your home directory you created in step 1.
Navigate to your home directory and make sure that the file ends with .java. If it ends
with .java.txt then delete the .txt part.

4. Go to Start Menu->Programs->Accessories and click on Command Prompt or MSDOS


Prompt. This is the command prompt where you’ll be running the commands to compile
and run your programs. At the prompt, change to your home directory by typing the
following command and pressing enter (where yourname stands for the name you gave
your folder):
cd c:\java\yourname

5. Compile the source code you wrote in Step 2 by now typing the following command at
the prompt and pressing enter:
javac HelloWorld.java
If running this command prints any errors to the command prompt window, then you
either did not copy the code in Step 2 correctly or you did not give the file the right name
in Step 3. Make sure each is copied precisely, character by character, with correct
capitalization, and then try to recompile. If it compiles successfully, it will print out
nothing and simply show the next prompt.

6. Now run your program by executing the following command at the command prompt:
java HelloWorld
What do you see?

7. Now change the HelloWorld code so that it prints out “Goodbye, World!” instead.
This should be done by changing only one line of your program. Compile and run your
program and see what it prints out.
8. The command System.out.println prints out its argument and then starts a new
line. Change your program so it prints out “Hello, World!” on one line and then prints out
“Goodbye, World!” on the next line. Compile and run.

9. Take a look at the code you have written. It begins by creating a class called
HelloWorld. We’ll learn more about what a class is in later lectures. After the word
HelloWorld in your code, there is an opening brace { which denotes the beginning of
the class. Then all the way at the bottom of your code there is a closing brace } which
denotes the end of the class.

10. Every Java file contains a class with the same name as the file. See how the class we
created called HelloWorld is in a file called HelloWorld.java? If we had a Java
file named Racecar.java, in it you would find a class called Racecar. If we were to
create a class called Student, we would create it in a file called Student.java.

11. Inside some classes, you’ll find what’s called the main method. The main method
always begins with the text:
public static void main(String[] args)
After this text you’ll see an opening brace { which denotes the beginning of the main
method and the second-to-last closing brace } denotes the end of the main method.
We’ll see a lot of things in Java begin and end with braces.

12. Add these lines to your main method:


String name = "AITI";
System.out.print("Hello,");
System.out.println(name);
System.out.println("How are you today?");
Compile and run. How does System.out.print differ from
System.out.println?

11. Change the text "AITI" to your name (for example, "Mark") and compile and run
your code again. How has the output changed?

12. Change the line


System.out.println(name)
to the line
System.out.println("name");
Why are the outputs different?

12. Play around with printing out different messages.


Java Lab 1: Variables & Operators

1. Correct the following statements:


a) boolean isGood = 1;
b) char firstLetter = p;
c) int 2way = 89;
d) String name = Manish;
e) int player score = 8976543;
f) Double $class = 4.5;
g) int _parents = 20.5;
h) string name = "Greg";

2. Without doing any programming, what do you think the following main method prints
to the screen?

public static void main(String[] args) {


int x = 5;
int y = 3;
int z = x + x*y - y;
System.out.println("The value of z is " + z);

int w = ++x + y + y--;


System.out.println("The value of w is " + w);
System.out.println("The value of x is now " + x);
System.out.println("The value of y is now " + y);

boolean a = true;
boolean b = false;
boolean c = ((a && (!(x > y))) && (a || y >x ));
System.out.println("c is " + c);
}

3. Create a new Java file with a class called UsingOperators and copy the above main
method into it. (Can you figure out what the name of the of the Java file must be? Hint: see
step 10 of Lab 0.) Compile and run. Does the output match what you thought?

4. Create a new Java class called TempConverter. Add a main method to


TempConverter that declares and initializes a variable to store the temperature in
Celsius. Your temperature variable should be store numbers with decimal places.

public class TempConverter{


public static void main(String [] args){
double temp = Double.paraseouble (args[0]);
}
}
5. In the main method, compute the temperature in Fahrenheit according to the following
formula and print it to the screen: Fahrenheit = (9 ÷ 5) × Celsius + 32

6. Set the Celsius variable to 100 and compile and run TempConverter. The correct
output is 212.0. If your output was 132, you probably used integer division somewhere by
mistake.
Java Lab 2: Control Structures

1. Create a new class called UsingControlStructures.

2. Add a main method to the class, and in the main method declare and initialize a
variable to represent a person's age.

3. In the main method, write an if-else construct to print out "You are old enough to
drive" if the person is old enough to drive and "You are not old enough to drive" if the
person is too young.

4. Write a for loop that prints out all the odd numbers from 100 to 0 in decreasing order.

5. Do Step 4 with a while loop instead of a for loop.


Java Lab 3: Gradebook – Part 1

1. Create a new class called Gradebook.

2. Add a main method of Gradebook. In the main method, declare and initialize an
array of doubles to store the grades of a student.

3. Write a loop to print out all the grades in the array. Make sure that your printout is
readable with spaces or new lines between each grade.

4. Write a new loop to find the sum of all the grades in the array.

5. Divide by the sum by the number of grades in the array to find the student's average.

6. Print a message to the user showing the average grade. If the average grade is 85.4, the
output should be "Your average grade is 85.4".

7. Your program should work if there are 4 grades in the array or 400 grades in the array.
That is, you should be able to change the number of grades in the initialized array and
compile, and it should run without any problems. Try it out. If it doesn't, figure out how
to rewrite your program so it does.

8. (Optional) Add code to print out the letter grade the student earned based on the
average grade. An average in the 90's is an A, in the 80's is a B, 70's is a C, 60's is a D,
and anything lower is an F.
Java Lab 4: Gradebook 2

1. Add a method to Gradebook called printGrades that accepts an array of doubles


as an argument and prints out all the grades in the array. Replace the loop in the main
method that prints out all the grades with a call to the printGrades method. Compile
and run.

2. Add a method to Gradebook called averageGrade that takes an array of doubles


as an argument and returns the average grade. Replace the loop and calculations in the
main method that determines the average grade with a call to the averageGrade
method. Your main method should still print out the user's average grade and the letter
grade the user earned. Compile and run.

3. Change the main method of Gradebook so that it converts its String arguments
into doubles and initializes the grades in the array to those numbers. Use the method
Double.parseDouble to convert a String containing a double to an actual
double. Compile and run and provide arguments at the command line, like this:
java Gradebook 82.4 72.5 90 96.8 86.1

4. (Optional) Copy the c:\java\EasyReader\EasyReader.class file into your


directory. EasyReader is a file we wrote for you that makes it easy to read data the
user types in. It has several methods, two of which are readInt and readDouble.
The readInt method waits for the user to type in an integer and press enter, and it
returns the integer the user types in. The readDouble does the same thing, but for
doubles.

To call the readInt or readDouble method, you have to type


EasyReader.readInt() or EasyReader.readDouble(). For example, to read
a double from the user and assign it to a variable d, you could use the following code:
double d = EasyReader.readDouble();

Try modifying your code so that instead of just taking the array of grades from the main
method, the program asks the user to enter the grades. Hint: use the two EasyReader
methods discussed!

5. (Optional) Change the main method so that after asking the user to enter the grades, it
prints out a menu of two options for them: 1) print out all the grades or 2) find the
average grade. It should ask the user to enter the number of their choice and do what the
user chooses.
Java Lab 5: GradebookOO – Part 1

1. In labs 3 and 4, we built a procedural gradebook program. In labs 5, 6 and 7, we're


going to write a new object-oriented gradebook program. Please look back as your
Gradebook class as needed for help in writing your new object-oriented gradebook.

2. Create a new class called GradebookOO (that's two O's for Object-Oriented). The
class should have a single field which is an array of doubles called grades. This
class will have no main method. Compile. Why can't you run this class?

3. Write two constructors for GradebookOO. This first should take no arguments and
initialize the grades field to an array of size zero. The second should take an argument
that is an array of doubles and assign that array to the field. Compile.

4. Add a method to GradebookOO named printGrades that takes no arguments and


prints out all the grades in the grades field. Compile.

5. Add a method to GradebookOO named averageGrade that takes no arguments


and returns the average grade in the grades field. Compile.

6. Create a new class called GBProgram. Add a main method to GBProgram which
instantiates a Gradebook with an array of grades, prints out all the grades with a call to
the printGrades method, and finds the average grade with the averageGrade
method. Compile and run.

7. (Optional) Use EasyReader, as described in Step 3 of the previous lab, in the main
method of GBProgram to allow the user to enter in the grades.

8. (Optional) Print out a menu to the user, as described in Step 4 of the previous lab, that
allows the user to select whether they would like to print out all the grades or find the
average grade.
Java Lab 6: GradebookOO – Part 2

1. Add appropriate access modifiers to all your fields and methods in GradebookOO
and GBProgram. Compile.

2. Add a method to GradebookOO called addGrade which accepts a double


argument and adds it to the array of grades. This is difficult. Two things you should note:
 arrays always have the same length, so you can't increase it the size of it
 arrays are objects not primitives, so variables of type array hold references to arrays

Here are the steps your addGrade method should follow:

a) When addGrade is called, the grades field holds a reference to an array of grades:
grades —————————————————————> [83.2, 97.4, 76.8]

b) Create a new array, maybe call it temp, that is a size 1 bigger than grades:
grades —————————————————————> [83.2, 97.4, 76.8]
temp —————————————————————> [ , , , ]

c) Copy over all the elements from grades into temp:


grades —————————————————————> [83.2, 97.4, 76.8]
temp —————————————————————> [83.2, 97.4, 76.8, ]

d) Add the new grade into the last slot of temp:


grades —————————————————————> [83.2, 97.4, 76.8]
temp —————————————————————> [83.2, 97.4, 76.8, 90.5]

e) Change grades so it points to the temp array:


grades —————————————————————> [83.2, 97.4, 76.8, 90.5]

3. Delete the GradebookOO constructor that takes an array of doubles as an argument.


And change the main method of GBProgram so that it instantiates an empty
GradebookOO and adds the grades one-by-one to it with the addGrade method.
Compile and run.

4. (Optional) If you have not done so in the past few labs, use EasyReader to read the
grades from the user and print out a menu to the user. See Steps 3 and 4 of Lab 4 for
more details.

5. (Optional) Add a method deleteGrade to GradebookOO which accepts a grade as


an argument and removes it from the array if it's there. This is tricky. Compile and run.
Java Lab 8: Racecar – Part 1

1. Create a new class called Racecar. Add two fields to Racecar: a field of type
String to store the name of the car and a field of type Color (from java.awt.Color)
to store the color of the car. Each car can have a different name and color. Should the
fields be static or non-static? Compile.

2. Every one of our racecars will have the same top speed. Add a private constant of type
double to the Racecar class to store the top speed and initialize it to any number you
want. Should this field be static or non-static? Compile.

3. Add a constructor to Racecar which accepts a name and color argument and assigns
the arguments to the name and color fields of the class. Compile.

4. Add a method called getName that returns the name of the car and a method called
getColor that returns the color of the car. Should these methods be static or non-static?
Compile.

5. Add a method to Racecar called race which accepts two Racecars as arguments,
simulates a race between the two, and returns the car that one the race, or return null if
the race is a tie. The method should calculate a random speed for each car between 0 and
the top speed. The car with the higher speed wins the race, but if they both have the same
speed they tie. The method random in java.lang.Math returns a random double
between 0 and 1. If you multiply this random number by the top speed, the product will
be a random number between 0 and the top speed. Should this method be static or non-
static? Compile.

6. Add a main method to Racecar which creates two Racecars, races them against
one another, and prints out the winner's name. When instantiating the Racecar objects,
pass one of the static fields of the Color class (like RED or BLUE) as the color argument
to the constructor. Should the main method be static or non-static? Compile and run.

7. (Optional) Instead of having a constant top speed for all racecars, change the
Racecar class so every car has its own top speed.

8. (Optional) Program a better racing simulation in the race method.


Java Lab 9: Racecar – Part 2

1. Create a new package called race. Move Racecar.java into the package folder
and add a package statement to Racecar to declare it a member of that package.
Compile and run.

2. Create a new package called easyreader. Copy EasyReader.java into the


package folder and add a package statement to EasyReader to declare it a member of
that package. Compile.

3. Add an import statement to Racecar that imports the EasyReader class. Compile
Racecar.

4. The file EasyReader.html file in the easyreader folder is the API for the
EasyReader class. Take at a look at it. Referencing the API as needed, change the
main method in Racecar to make a more interactive racing game. If you want, you
could allow users to choose the color and speed of their cars and construct races. Or you
could do something completely different. Be creative. Feel free to change the Racecar
class or add other classes to the race package.
Java Lab 10: Students – Part 1

1. Create a package called students. All the classes you create in this and the next lab
will be created in this package. You should compile after each of the following steps.

2. Create a class called Student, which should have two properties, a name and a year
and methods to get the name and get the year of the student. Initialize these properties to
arguments passed into the constructor.

3. Create a subclass of Student called Undergrad. The Undergrad constructor


should accept name and year arguments. Add a method to Undergrad called
description which returns a String containing the name of the undergrad, then a
space, then a capital 'U', then a space, and then the year of the undergrad. For example,
the description method of an Undergrad instance with the name "Michael" and
the year 2006, should return the String "Michael U 2006".

4. Create a subclass of Student called Grad. The Grad constructor should accept only
the name of the Grad as an argument, and it should always initialize the Grad's year to
5. Add a description method to Grad which returns a String containing the name
of the Grad, followed by a space and then the letter 'G'. The description method of
a Grad named "Jennifer" should return the String "Jennifer G".

5. Create a subclass of Undergrad called Intern. In addition to the name and year
properties, Intern should have a wage and a number of hours that are initialized in the
constructor. Add a getPay method to Intern which returns the wage times the
number of hours. Add a description method to Intern which returns a String
containing the result of calling Undergrad's description method followed by the return
value of the getPay method. The description method of an Undergrad named
"Elizabeth" whose year is 2005 and worked 20 hours at $10.32/hour, should return the
String "Elizabeth U 2005 206.4".

6. Create a subclass of Grad called ResearchAssistant. ResearchAssistant


has a salary that is initialized in the constructor and a getPay method that returns the
salary. Add a description method to ResearchAssistant which returns a
String containing the result of Grad's description method, followed by the result
of getPay. The description method of a ResearchAssistant with the name
"Greg" and a $2000.00 salary would return the String "Greg G 2000.0".

7. Create a class called StudentTest that has a main method. Use the main method to
test the class hierarchy you just built. Create some instances of Undergrad, Grad,
Intern, and Research Assistant. Print out the result of their description
methods. Compile and run.
Java Lab 11: Students – Part 2

1. A university tells you they want to use the student objects that you built in their new
software system. For the rest of the lab, you will be improving your student objects to
meet the needs of the university.

2. The university wants to be able to easily print out descriptions of every student. In the
main method of StudentTest, add the instances of Undergrad, Grad, Intern,
and Research Assistant that you created in the last lab to an ArrayList. Iterate
through the ArrayList, cast each element to a Student and print out the return value
of the description method of each. Try to compile. The call to the description
method should generate a "cannot resolve symbol" error. Why?

3. Fix the error by adding a dummy description method to Student which returns
null. Compile and run.

4. The university tells you that they do not want the Student class to be instantiated,
and they want to guarantee that every subclass of Student implements the
description method. Change the Student class so it meets these two
requirements. Compile and run.

5. The university wants to be able to use your objects in their student payroll system.
They need to be able to easily print out the pay of all the interns and research assistants.
In the main method of StudentTest, create an ArrayList with just Interns and
ResearchAssistants. Is it possible to iterate through the ArrayList, cast each to
a Student, and call getPay on each?

5. Create an Employee interface with a single method, getPay. Have Intern and
ResearchAssistant implement that interface. Now iterate through your list of
employees and print out the pay of each.

6. (Optional) Write a program that the university can use to manage its students. The
program can do whatever you want, so long as you think the university would find it
useful. For example, it could print out a menu of options and allow the user to create all
different types of students and print out the description of students and the pay of all the
student employees. You can add new properties to your students or create new types of
students if you wish. Be creative.
Java Lab 12: MyStore – Part 1

1. In the next two labs you will write software to run a store. The store can sell any
products you want – it's up to you. Begin by creating a new package called store. All
the classes you create in the next two labs will go in this package.

2. Create a new class called Product. This will represent a product sold in your store.
Add fields to the Product class to store the name and price of the product. These fields
should be assigned to values passed as arguments into the constructor. Add methods to
Product to return the name and price of the product. Compile.

3. Change the Product constructor so it throws a NullPointerException is the


name is null and an IllegalArgumentException if the price is negative.
Compile.

4. Create a new class called MyStore. MyStore should have a list field to contain all
the products in your store. Initialize the field to an empty list in the MyStore
constructor. Compile.

5. Add a method to MyStore called readProducts. This method should accept no


arguments and return nothing. In the readProducts method, print messages to the
console that ask the user to enter in a product name and price, and then read the name and
price with EasyReader. Instantiate a Product with that name and price and add that
product to the list of products. Compile.

6. Add a main method to MyStore. In the main method, instantiate a MyStore object
and call the readProducts method on that object. Compile and run.

7. What happens when you type a word instead of a number when your program asks you
to type in a price?

8. Write a new checked exception called ProductException. Make sure you write
both types of exception constructors. Compile.

9. Change the readProducts method in MyStore so that it catches the


NumberFormatException thrown by EasyReader and throws a
ProductException inside the catch clause. Change the main method in MyStore so
that it catches a ProductException and prints out an appropriate message to the user.
Compile and run.
Java Lab 13: MyStore – Part 2

1. Using Notepad, start a new text file and save it as products.txt to the parent
directory of the store package. On each line of the file, write the name of a product you
want your store to sell, a '$' symbol, and then the price of the product. For example, if
you want your store to sell a computer for 1500.45 and a soccer ball for 37.23, make sure
your products.txt file has the following two lines:

computer$1500.45
soccer ball$37.23

Your products.txt file should list at least 10 products.

2. Add a method to MyStore called readProductsFromFile. The method should


accept one argument, a String containing a filename. Open the file with that filename
using a FileReader and wrap the FileReader in a BufferedReader to read the
file line-by-line. For each line of the file, create a StringTokenizer that will split the
line at '$' characters. Use the tokenizer to get name and price of the product. Then convert
the price from a String to a number and instantiate a Product object with that name
and price. Finally, add that product to the store's list of products. Catch any
IOExceptions thrown by the above operations and throw a ProductException in
the catch clause. Compile.

3. In the main method of MyStore, call the readProductsFromFile method on


the store instance you created and pass the String "products.txt" as an argument
to the method. Compile and run.

4. (Optional) Write an interface called ProductSource which has a single method,


getProducts that accepts no arguments and returns a list of products. Write two
classes that implement ProductSource. The first, called KeyboardSource, should
have an empty constructor. Its getProducts method should ask the user to type in
some products the same way your readProducts method does, and it should return a
list of products that the user typed in. The second class, FileSource, should accept a
filename argument, and its getProducts method should read products from the file
like the readProductsFromFile method and return a list of products in the file.
Compile.

7. (Optional) Replace the readProducts and readProductsFromFile method


with a single method loadProducts method that accepts a ProductSource
argument. The loadProducts method should call getProducts on the
ProductSource and add the products returned by the ProductSource to the store's
list of products. Hint: using the addAll method provided by lists should make your life
easier. Compile.

8. (Optional) Change the main method of MyStore to use KeyboardSource,


FileSource, and the loadProducts method instead of the readProducts and
readProductsFromFile methods. Why is this a better design?
Java Lab 16: Card Game – Part 1

1. In the next two labs, you will be helping to build a card game program. The program
allows the user to play the Ghanaian card game Spa against three other opponents. Most
of the code has already been written for you, but you have to complete some very
important parts before it will work.

2. Look at the class CardSuit.java in the spa.card package. A comment in the


class says that there are exactly four instances of CardSuit. Why can't more instances
of CardSuit be created? Why doesn't this class need to override the equals method?
How would another class refer to the Diamonds suit?

3. Change CardSuit so that it implements the Comparable interface. The


comparison of card suits should follow this ranking: spades > diamonds > hearts > clubs.
Compile CardSuit.java.

4. Correctly implement the equals and compareTo methods in Card.java. Read


the comment above the compareTo method to see how the cards should be compared.

5. Add a field to Deck.java to store all the cards in the Deck. We want to be able to
draw cards from the Deck, sort the deck, and shuffle the deck. What should the type of
the field be and why?

6. Correct implement the Deck constructor. Hint: do not write 52 lines, each of which
creates and adds a different card; instead, use the two public arrays declared by Card to
accomplish this with less code.

7. Correcty implement every other method in Deck except for hashCode. Hint: you can
write the sort and shuffle methods in one line if you know where to look.
Java Lab 17: Card Game – Part 2

1. Correctly implement the hashCode method in Card.java.

2. Correctly implement the hashCode method in Deck.java.

3. Add a field to Hand.java to store all the cards in a hand. As Hand.java shows,
we want the ability to add and remove cards from the hand. What should the type of the
field be and why?

4. Correctly implement all the methods in Hand.java.

5. Compile all your code and run spa.graphics.SpaGui to play!

Here are some brief playing instructions:

Everyone is dealt 5 cards, no card less than a 6 is dealt out. Every player, moving
clockwise, chooses a card to play. You must play a card in the same suit that was lead if
you have one; otherwise, you can play any card. Once everyone has played a card, the
highest card in the suit that was lead wins the trick. If you win a trick, you lead (play the
first card) of the next trick. The player who wins the last trick (the 5 th trick) of the round,
wins the entire round.

If you are dealt a 6 or a 7, you will be asked if you want to dry one of those cards. If you
dry a 7 and you win the round (win the last trick) with that 7, you score 3 points total. If
you dry a 6 and you win the round with that 6, you score 2 points. If you win the round
with any other card, you score 1 point.

In our version, the first player to reach 5 points wins the game.
package cards;

public class CardSuit implements Comparable {

public static final CardSuit SPADES = new CardSuit("spades");


public static final CardSuit HEARTS = new CardSuit("hearts");
public static final CardSuit DIAMONDS = new CardSuit("diamonds");
public static final CardSuit CLUBS = new CardSuit("clubs");

private String name;

private CardSuit(String name) {


this.name = name;
}

public String getName() {


return name;
}

public int compareTo(Object o) {


CardSuit cs = (CardSuit)o;
if (this == cs) return 0;
else if (this == SPADES || cs == CLUBS) return 1;
else if (this == CLUBS || cs == SPADES) return -1;
else if (this == HEARTS) return 1;
else return -1;
}
}

S-ar putea să vă placă și