Programming Exercises

graphics/pe_icon.gif

2.1

The following program has several errors. Modify it so that it will compile and run without errors. (See Section 4.6 on page 129 for compiling and running code from packages.)

import java.util.*;

package com.acme;

public class Exercise1 {
    int counter;

    void main(String[] args) {
        Exercise1 instance = new Exercise1();
        instance.go();
    }

    public void go() {
        int sum;
        int i = 0;
        while (i<100) {
            if (i == 0) sum = 100;
            sum = sum + i;
            i++;
        }
        System.out.println(sum);
    }
}
2.2

The following program has several errors. Modify it so that it will compile and run without errors.

// Filename: Temperature.java
PUBLIC CLASS temperature {
    PUBLIC void main(string args) {
        double fahrenheit = 62.5;
        */ Convert /*
        double celsius = f2c(fahrenheit);
        System.out.println(fahrenheit + 'F = ' + celsius + 'C');
    }

    double f2c(float fahr) {
        RETURN (fahr - 32) * 5 / 9;
    }
}