You are on page 1of 21

Solutions to Java Lab 0

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.

public class HelloWorld {


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

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.

public class HelloWorld {


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

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?

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, Mark" instead of "Hello, AITI".

12. Change the line System.out.println(name)


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

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

1. Correct the following statements:


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

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

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.

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

public class TempConverter {


public static void main(String[] args) {
double celcius = 100.0;
double fahrenheit = (9.0 / 5.0) * celcius + 32;
System.out.println(fahrenheit);
}
}

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

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.

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.

for (int i = 100; i > 0; i--) {


if (i % 2 == 1) {
System.out.println(i);
}
}
or

for (int i = 99; i > 0; i -= 2) {


System.out.println(i);
}

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

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

public class Gradebook {

public static void main(String args[]) {

double[] grades = {82.4, 72.5, 90, 96.8, 86.1};

for(int i = 0; i < grades.length; i++) {


System.out.println(grades[i]);
}

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

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

public class Gradebook {

public static void printGrades(double[] grades) {


for(int i = 0; i < grades.length; i++) {
System.out.println(grades[i]);
}
}

public static double averageGrade(double[] grades) {


double total = 0;
for(int i = 0; i < grades.length; i++) {
total += grades[i];
}
return total / grades.length;
}

public static void main(String args[]) {


double[] grades = new double[args.length];
for (int i = 0; i < grades.length; i++) {
grades[i] = Double.parseDouble(args[i]);
}

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.

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 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!

public static void main(String args[]) {

System.out.print("How many grades do you want to enter? ");


int numGrades = EasyReader.readInt();
double[] grades = new double[numGrades];

for (int i = 0; i < grades.length; i++) {


System.out.print("Enter grade #" + (i + 1) + ": ");
grades[i] = EasyReader.readDouble();
}

. . .
}
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.

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.

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 {

public static void main(String args[]) {

double[] grades = new double[args.length];


for (int i = 0; i < args.length; i++) {
grades[i] = Double.parseDouble(args[i]);
}

GradebookOO gbook = new GradebookOO(grades);


gbook.printGrades();
double average = gbook.averageGrade();
System.out.println("Your average grade is " +
average);
}
}

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.

public static void main(String args[]) {

System.out.print(
"How many grades do you want to enter? ");
int numGrades = EasyReader.readInt();
double[] grades = new double[numGrades];

for (int i = 0; i < grades.length; i++) {


System.out.print("Enter grade #" + (i + 1) + ": ");
grades[i] = EasyReader.readDouble();
}

. . .
}
Solutions to Java Lab 6

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

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.

class GradebookOO {

private double grades[];

public GradebookOO() {
grades = new double[0];
}

public void printGrades() {


for(int i = 0; i < grades.length; i++) {
System.out.println(grades[i]);
}
}

public double averageGrade() {


double total = 0;
for(int i = 0; i < grades.length; i++) {
total += grades[i];
}
return total / grades.length;
}

public void addGrade(double g) {


double[] temp = new double[grades.length + 1];
for(int i = 0; i < grades.length; i++) {
temp[i] = grades[i];
}
temp[grades.length] = g;
grades = temp;
}
}
class GBProgram {

public static void main(String args[]) {

GradebookOO gbook = new GradebookOO();


for (int i = 0; i < args.length; i++) {
double g = Double.parseDouble(args[i]);
gbook.addGrade(g);
}

gbook.printGrades();
double average = gbook.averageGrade();
System.out.println("Your average grade is " +
average);
}
}

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.

public void deleteGrade(double g) {


int gIndex = 0;
for(; gIndex < grades.length; gIndex++) {
if (grades[gIndex] == g) break;
}

if (gIndex == grades.length) return;

double[] temp = new double[grades.length - 1];


for(int i = 0; i < gIndex; i++) {
temp[i] = grades[i];
}
for(int i = gIndex + 1; i < grades.length; i++) {
temp[i - 1] = grades[i];
}

grades = temp;
}
Solutions to Java Lab 7

1. Change the field in the GradebookOO program from an array to an ArrayList.

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 {

private ArrayList grades;

public GradebookOO() {
grades = new ArrayList();
}

public void printGrades() {


Iterator gradeIter = grades.iterator();
while(gradeIter.hasNext()) {
double grade = ((Double)gradeIter.next()).doubleValue();
System.out.println(grade);
}
}

public double averageGrade() {


double total = 0;
Iterator gradeIter = grades.iterator();

while(gradeIter.hasNext()) {
double grade = ((Double)gradeIter.next()).doubleValue();
total += grade;
}

return total / grades.size();


}

public void addGrade(double g) {


grades.add(new Double(g));
}
}

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;

public class Racecar {


private final static double TOP_SPEED = 300.0;
private String name;
private Color color;

public Racecar(String name, Color color) {


this.name = name;
this.color = color;
}

public String getName() {


return name;
}

public Color getColor() {


return color;
}

public static Racecar race(Racecar r1, Racecar r2) {


double r1speed = Math.random() * TOP_SPEED;
double r2speed = Math.random() * TOP_SPEED;

if (r1speed > r2speed) {


return r1;
} else if (r1speed < r2speed) {
return r2;
} else {
return null;
}
}

public static void main(String args[]) {


Racecar a = new Racecar("Corvette", Color.BLUE);
Racecar b = new Racecar("Porsche", Color.RED);
Racecar winner = race(a, b);

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;

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.

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;

public class Student {

private String name;


private int year;

public Student(String name, int year) {


this.name = name;
this.year = year;
}

public String getName() {


return name;
}

public int getYear() {


return year;
}
}

package students;

public class Undergrad extends Student {

public Undergrad(String name, int year) {


super(name, year);
}

public String description() {


return getName() + " U " + getYear();
}
}

package students;

public class Grad extends Student {

public Grad(String name) {


super(name, 5);
}

public String description() {


return getName() + " G";
}
}
package students;

public class Intern extends Undergrad {

private double wage;


private int numHours;

public Intern(String name, int year,


double wage, int numHours) {
super(name, year);
this.wage = wage;
this.numHours = numHours;
}

public double getPay() {


return wage * numHours;
}

public String description() {


return super.description() + " " + getPay();
}
}

package students;

public class ResearchAssistant extends Grad {

private double salary;

public ResearchAssistant(String name, double salary) {


super(name);
this.salary = salary;
}

public double getPay() {


return salary;
}

public String description() {


return super.description() + " " + getPay();
}
}

package students;

public class StudentTest {

public static void main(String args[]) {


Undergrad u = new Undergrad("Michael", 2006);
System.out.println(u.description());

Grad g = new Grad("Jennifer");


System.out.println(g.description());

Intern i = new Intern("Elizabeth", 2005, 10.32, 20);


System.out.println(i.description());

ResearchAssistant r = new ResearchAssistant("Greg", 2000.00);


System.out.println(r.description());
}
}
Solutions to Java Lab 11

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?

No, because Student does not have a getPay method.

package students;

public abstract class Student {

. . .

public abstract String description();


}

package students;

public interface Employee {

public double getPay();

package students;

public class Intern extends Undergrad implements Employee {


. . .
}
package students;

public class ResearchAssistant extends Grad


implements Employee {
. . .
}

package students;

import java.util.ArrayList;
import java.util.Iterator;

public class StudentTest {

public static void main(String args[]) {


Undergrad u = new Undergrad("Michael", 2006);
Grad g = new Grad("Jennifer");
Intern i = new Intern("Elizabeth", 2005, 10.32, 20);
ResearchAssistant r =
new ResearchAssistant("Greg", 2000.00);

. . .

ArrayList employees = new ArrayList();


employees.add(i);
employees.add(r);

Iterator empIter = employees.iterator();


while(empIter.hasNext()) {
double pay = ((Employee)empIter.next()).getPay();
System.out.println(pay);
}
}
}
Solutions to Java Lab 12

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.

package store;

public class Product {

private String name;


private double price;

public Product(String name, double price) {


if (name == null) {
throw new NullPointerException(
"name cannot be null");
}
if (price < 0) {
throw new IllegalArgumentException(
"price cannot be negative");
}

this.name = name;
this.price = price;
}

public String name() {


return name;
}

public double price() {


return price;
}
}
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.

package store;

import easyreader.EasyReader;
import java.util.ArrayList;

public class MyStore {

private ArrayList products = new ArrayList();

public MyStore() {
products = new ArrayList();
}

public void readProducts() {


System.out.print("Enter the name of the product: ");
String name = EasyReader.readLine();
System.out.print("Enter the price of the product: ");
double price = EasyReader.readDouble();

Product p = new Product(name, price);


products.add(p);
}

public static void main(String args[]) {


MyStore st = new MyStore();
st.readProducts();
}
}

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

EasyReader throws a NumberFormatException


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

package store;

public class ProductException extends Exception {

public ProductException() {}

public ProductException(String msg) { super(msg); }

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.

public void readProducts() throws ProductException {


try {
System.out.print("Enter the name of the product: ");
String name = EasyReader.readLine();
System.out.print("Enter the price of the product: ");
double price = EasyReader.readDouble();
Product p = new Product(name, price);
products.add(p);
} catch (NumberFormatException e) {
throw new ProductException("not a valid price");
}
}

public static void main(String args[]) {


MyStore st = new MyStore();

try {
st.readProducts();
} catch(ProductException e) {
System.out.println("Error reading products");
}
}
Solutions to Java Lab 13

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.

public void readProductsFromFile(String filename)


throws ProductException {
try {
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();

while (line != null) {


StringTokenizer st = new StringTokenizer(line, "$");
String name = st.nextToken();
double price = Double.parseDouble(st.nextToken());
Product p = new Product(name, price);
products.add(p);
line = br.readLine();
}

br.close();
} catch (IOException e) {
throw new ProductException("error reading from file");
}
}

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.

try {
st.readProductsFromFile("products.txt");
} catch(ProductException e) {
System.out.println("Error reading products");
}

You might also like