Professional Documents
Culture Documents
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.
The println method starts a new line after printing out its argument and print
does not.
11. Change the text "AITI" to your name (for example, "Mark") and compile and run
your code again. How has the output changed?
The output now says "Hello, name" instead of "Hello, Mark". In the first line, the
name variable is passed to println and its value is printed out. In the second, the
String "name" is passed as an argument, and that String is printed.
Solutions to Java Lab 1
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?
The value of z is 17
The value of w is 12
The value of x is now 6
The value of y is now 2
c is false
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
7. Set the Celsius variable to 100 and compile and run TempConverter. The correct
output is 237.6. If your output was 132, you probably used integer division somewhere by
mistake.
if both 9 and 5 are used instead of 9.0 and 5.0 in the formula, then the program will
print out the incorrect answer of 132
Solutions to Java Lab 2
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.
class UsingControlStructures {
public static void main(String[] args) {
int age = 15;
if (age >= 18) {
System.out.println("You are old enough to drive.");
} else {
System.out.println("You are not old enough to drive.");
}
}
}
4. Write a for loop that prints out all the odd numbers from 100 to 0 in decreasing order.
int i = 100;
while(i > 0) {
if (i % 2 == 1) {
System.out.println(i);
}
i--;
}
or
int i = 99;
while(i > 0) {
System.out.println(i);
i--;
}
Solutions to Java Lab 3
double total = 0;
for(int i = 0; i < grades.length; i++) {
total += grades[i];
}
double average = total / grades.length;
System.out.println("Your average grade is " +
average);
// OPTIONAL:
char letterGrade;
if (average >= 90) {
letterGrade = 'A';
} else if (average >= 80) {
letterGrade = 'B';
} else if (average >= 70) {
letterGrade = 'C';
} else if (average >= 60) {
letterGrade = 'D';
} else {
letterGrade = 'F';
}
System.out.println("Your letter grade is " +
letterGrade);
}
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.
If the number of grades in the array (in this case 5) were used in place of
grades.length in either of the three places grades.length is used, the code would not
work for different sizes of the grades array.
Solutions to Java Lab 4
printGrades(grades);
double average = averageGrade(grades);
System.out.println("Your average grade is " + average);
// OPTIONAL:
char letterGrade;
if (average >= 90) {
letterGrade = 'A';
} else if (average >= 80) {
letterGrade = 'B';
} else if (average >= 70) {
letterGrade = 'C';
} else if (average >= 60) {
letterGrade = 'D';
} else {
letterGrade = 'F';
}
System.out.println("Your letter grade is " + letterGrade);
}
}
3. (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.
Try modifying your code so that instead of just assigning the array of grades in the main
method, the program asks the user to enter the grades. Hint: use the two EasyReader
methods discussed!
. . .
}
Solutions to Java Lab 5
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.
class GradebookOO {
double grades[];
GradebookOO() {
grades = new double[0];
}
GradebookOO(double[] grades) {
this.grades = grades;
}
void printGrades() {
for(int i = 0; i < grades.length; i++) {
System.out.println(grades[i]);
}
}
double averageGrade() {
double total = 0;
for(int i = 0; i < grades.length; i++) {
total += grades[i];
}
return total / grades.length;
}
}
6. Create a new class called GBProgram. Add a main method to GBProgram which
instantiates a Gradebook with an array of grades converted from the Strings passed
as arguments to the main method, prints out all the grades with a call to the
printGrades method, and finds the average grade with the averageGrade method.
Compile and run.
class GBProgram {
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.
System.out.print(
"How many grades do you want to enter? ");
int numGrades = EasyReader.readInt();
double[] grades = new double[numGrades];
. . .
}
Solutions to Java Lab 6
1. Add appropriate access modifiers to all your fields and methods in GradebookOO
and GBProgram. Compile.
class GradebookOO {
public GradebookOO() {
grades = new double[0];
}
gbook.printGrades();
double average = gbook.averageGrade();
System.out.println("Your average grade is " +
average);
}
}
grades = temp;
}
Solutions to Java Lab 7
2. Rewrite all the methods to use the ArrayList instead of the array. Make sure you
use an Iterator for all the iterations through the ArrayList. Compile.
import java.util.ArrayList;
import java.util.Iterator;
class GradebookOO {
public GradebookOO() {
grades = new ArrayList();
}
while(gradeIter.hasNext()) {
double grade = ((Double)gradeIter.next()).doubleValue();
total += grade;
}
3. Do you have to make any changes to GBProgram so that it will compile and run
successfully? Why or why not?
No, you should not, because the GradebookOO object is treated as an abstraction.
All the implementation details have been made private, while the interface provided
by the methods is public.
Solutions to Java Lab 8
import java.awt.Color;
if (winner == null) {
System.out.println("The race is a tie");
} else {
System.out.println(winner.getName() + " won!");
}
}
}
Solutions to Java Lab 9
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.
package race;
package easyreader;
3. Add an import statement to Racecar that imports the EasyReader class. Compile
Racecar.
import easyreader.EasyReader;
Solutions to Java Lab 10
package students;
package students;
package students;
package students;
package students;
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?
Even though every object in the list has a description method, Java does not know
this. After casting the object in the list to type Student, you are only allowed to call
methods on it that are in Student, and Student does not have a description method.
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?
package students;
. . .
package students;
package students;
package students;
import java.util.ArrayList;
import java.util.Iterator;
. . .
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.
package store;
this.name = name;
this.price = price;
}
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.
package store;
import easyreader.EasyReader;
import java.util.ArrayList;
public MyStore() {
products = new ArrayList();
}
7. What happens when you type a word instead of a number when your program asks you
to type in a price?
package store;
public ProductException() {}
try {
st.readProducts();
} catch(ProductException e) {
System.out.println("Error reading products");
}
}
Solutions to Java Lab 13
br.close();
} catch (IOException e) {
throw new ProductException("error reading from file");
}
}
try {
st.readProductsFromFile("products.txt");
} catch(ProductException e) {
System.out.println("Error reading products");
}