Plain text version | Style: Default, Black and White, Bath

University of Bath Logo
Dr Marina De Vos
Department of Computer Science
Saturday, 25-Nov-2017 04:05:00 GMT

Programming I (CM10134 - CM50147): Lab 7

You will need to show all your code for the following exercises. It is still a good idea to read through the chapters in BlueJ and try out some of the exercises in there. However, these will no longer be checked.


  • Inheritance and Polymorphism
    Design and implement an inheritance hierarchy for the classes Shape, Triangle, Square and Rectangle. The classes should (at least) contain a method to calculate the surface area of the shape and a toString method.
    The driver program (which includes the main function) should create one of each of the shapes and store them in a collection. A loop should then be used to print out the details of the shape (dimensions and surface area) making use of polymorphism.
    (Further exercise: ask the user how many shapes they want to create and use this number to randomly create the objects.)


  • Writing and Reading from files
    Examine the following code that allows you to write and read Strings to and from file. Use this code to write sentences given by the user to a file. Each new input should be on a new line. The character for a new line is '\n'. The user should be able to keep typing in new sentences until they type "end". When the user has finished, read the content of the file and print it in reverse order.
    import java.io.*; //input and output classes
    
    public class Writing
    {
        public static void main(String[] args){
    
            /**
            * Do not worry about understanding try or catch. These will be covered in a later lecture..
            */
            try {
    
                FileWriter writer = new FileWriter("m.txt",true);
                writer.write("Marina\n");
                writer.close();
                BufferedReader reader = new BufferedReader(new FileReader("c://m.txt"));
                String line = reader.readLine();
                System.out.println(line);
                reader.close();
            }
            catch(IOException e) {
            
                System.out.println("nn");
            }
        }
    }