Teaching Problem Solving€¦ · Program your robot to move forward until the ultrasonic sensor...

16
Teaching Problem Solving COMPUTING

Transcript of Teaching Problem Solving€¦ · Program your robot to move forward until the ultrasonic sensor...

Page 1: Teaching Problem Solving€¦ · Program your robot to move forward until the ultrasonic sensor detects an object within 25cm of it. At this point it should stop. 2. Calibrate your

Teaching

Problem

Solving

COMPUTING

Page 2: Teaching Problem Solving€¦ · Program your robot to move forward until the ultrasonic sensor detects an object within 25cm of it. At this point it should stop. 2. Calibrate your

Basic NXT Blocks

Loops

Switch

Inset September 2011– Teaching Programming, a possible methodology—Marlene Galea

Display Block Move Block Sound Block

Wait Block Lamp Block Timer Block

Loop for

given time Loop forever Loop until

sensor input

Loop for x

times

Loop until

logic input

Flat view Tabbed View

My block

1. Select the program segment and

click ‘my block’.

2. Fill in details in the dialog box

3. Select the icons to make up your

button.

Page 3: Teaching Problem Solving€¦ · Program your robot to move forward until the ultrasonic sensor detects an object within 25cm of it. At this point it should stop. 2. Calibrate your

A Mini Golfer that hits a red ball but not a blue one

HINT! You may use the Robot Educator.

1. Program your robot to move forward until the ultrasonic sensor detects an object within 25cm of it. At this

point it should stop.

2. Calibrate your light sensor to be able to tell the red ball from the blue one.

3. Edit your program so that once your robot stops because of an object less than 25cm away:

• If the light sensor detects the red ball, the robotic arm should hit it and the robotic car should output an

‘Applause’ sound.

• If it detects the blue ball, the robotic arm should not hit it and output a ‘No’ sound.

4. The robotic car should now move back 3 rotations.

5. Make the above loop indefinitely.

Addressing safety issues

6. Modify your program so that:

• If a red ball is detected the LCD outputs: the text ‘Red Ball’

• If a blue ball is detected the LCD outputs: a ‘Stop’ image and underneath the text ‘Blue Ball’

7. Make your program loop a total of 5 times.

8. The robot should give a warning before moving the arm to hit the red ball by:

• Flashing the light sensor three times (high intensity) for visible notification.

• Playing an alerting sound file (volume 100).

Program Readability

9. Use a block to represent the contents of your switch

10. Use the ‘Comment’ tool to explain key parts in your program (particularly the function of the Block you created).

Basic Level

Advanced Level

Expert Level

Inset September 2011– Teaching Programming, a possible methodology—Marlene Galea

Page 4: Teaching Problem Solving€¦ · Program your robot to move forward until the ultrasonic sensor detects an object within 25cm of it. At this point it should stop. 2. Calibrate your

The Data Tab

Reading Data from Sensors

Data Wires Data wires allow data to be transferred between blocks

Inset September 2011– Teaching Programming, a possible methodology—Marlene Galea

Logic Compare Random Constant

Variable Range Math

Sound Sensor Touch

Sensor Ultrasonic

Sensor Light Sensor NXT Buttons

Output

plug Input

plug

Page 5: Teaching Problem Solving€¦ · Program your robot to move forward until the ultrasonic sensor detects an object within 25cm of it. At this point it should stop. 2. Calibrate your

Outputting distance from nearest object

1. Create a program that generates a random number between 1 and 3. This number should be the radius of the

attention (!) image now output on the screen.

2. Make your NXT read and output the distance from the nearest object directly in front of it. This distance should

be output as ‘x cm’ below the (!) image already on the screen.

Taking three Readings

3. Edit your program such that the NXT takes and outputs three readings of the distance from the nearest object.

4. It should output an attention sound between readings.

5. Before every reading it should also output the loop counter.

Choosing the best route

6. Your NXT should now turn 900 left and check the distance from the nearest object directly in front of it.

7. Your NXT should decide on the best route (between forward and left) and turn towards it.

The best route is the one where obstacles are least near.

8. Your NXT should now move forward until it is 25cm from the nearest obstacle and then stop and turn 900 left.

9. Loop the above 3 steps indefinitely.

Basic Level

Advanced Level

Expert Level

Inset September 2011– Teaching Programming, a possible methodology—Marlene Galea

Page 6: Teaching Problem Solving€¦ · Program your robot to move forward until the ultrasonic sensor detects an object within 25cm of it. At this point it should stop. 2. Calibrate your

Teaching

Object

Oriented

Programming

COMPUTING

Page 7: Teaching Problem Solving€¦ · Program your robot to move forward until the ultrasonic sensor detects an object within 25cm of it. At this point it should stop. 2. Calibrate your

Inset September 2011 – Teaching Programming, a possible methodology—Marlene Galea

A Simple Class

This is the class Vehicle, it has 4 properties as shown and one method called showVehicle():

Inheritance

The class Bus extends Vehicle, and has an additional variable called capacity. Therefore the class Bus looks like

this:

The Constructor Method

The Constructor method has the same name as the class and no return type (not even void)

The Main Method, Creating an instance of a class, Calling Methods

Escape Characters

public class Vehicle { String regNumber; int regYear; String model;

public void showVehicle(){ System.out.println (“Registration Number: ” + this.regNumber);

System.out.println (“Year: ” + this.regYear);

System.out.println (this.model);

}

}

class VehicleApp{ public static void main (String args[]){ Bus BusA= new Bus(); BusA.regNumber = "ABC123"; BusA.capacity = 50; BusA.showVehicle( ); } }

Declaring BusA, an object of class Bus.

Putting the values in the object vari-

ables.

Main method declaration

Escape Meaning

\n New line

\t Tab

public Bus ( ) { ... }

class Bus extends Vehicle { int capacity; }

Calling the method showVehicle for BusA

Page 8: Teaching Problem Solving€¦ · Program your robot to move forward until the ultrasonic sensor detects an object within 25cm of it. At this point it should stop. 2. Calibrate your

Inset September 2011 – Teaching Programming, a possible methodology—Marlene Galea

Encapsulation

1. Declare class attributes as private.

2. Make class attributes accessible only through setter and getter methods.

3. Access these private attributes through their setter and getter methods.

Passing person details to the class setter methods for object ‘person’

Using getter methods to obtain details.

public class Person{ private String name; private String surname; private String telNum; private String address;

public String getName(){ return this.name; } public String getSurname(){ return this.surname; } public String getTelNum(){ return this.telNum; } public string getAddress(){ Return this.address; }

public void setName(String name){ this.name = name; }

public void setSurname (String surname){ this.surname = surname; }

public void setTelNum (String TelNum){ if (telNum.length() !=8){ this.telNum = "None Supplied"; } else { this.telNum = telNum; } }

public void setAddress (String address){ this.address=address;

}

person.setName("Joseph"); person.setSurname ("Borg"); person.setAddress (personAddress); person.setTelNum (telNumber);

System.out.println ("Name: " + this.getName()); System.out.println ("Surname: " + this.getSurname()); System.out.println ("Address: " + this.getAddress());

Page 9: Teaching Problem Solving€¦ · Program your robot to move forward until the ultrasonic sensor detects an object within 25cm of it. At this point it should stop. 2. Calibrate your

A simple directory entry

1. Create a class called Entry having the properties shown above.

2. In class Entry, create a method called displayObject() to output the details of an object of that class.

3. Create a class DirectoryApp with a main method that creates a class instance and assigns its object variables

values from within the program.

4. From the main method call the displayObject() method for your Entry object.

Implementing inheritance in our application

5. Create Business, class extending Entry, that also has the property businessName.

6. In class Business, create a method called displayBusiness() to output details of a Business object.

7. Create an instance of class Business.

8. Call the displayBusiness() method for your Business object from the main method.

Improving our application: improving display and introducing information-hiding

9. Use escape characters to improve the presentation of your Entry and Business output details.

10. Create a simple constructor method for both classes.

11. Implement encapsulation in all classes.

Basic Level

Advanced Level

Expert Level

Class: Entry

+ name: String

+ surname: String

+ address: String

+ telNum: String

+ pendingLastMonth:double

+ paidThisMonth: double

+ billThisMonth: double

Inset September 2011– Teaching Programming, a possible methodology—Marlene Galea

Page 10: Teaching Problem Solving€¦ · Program your robot to move forward until the ultrasonic sensor detects an object within 25cm of it. At this point it should stop. 2. Calibrate your

Inset September 2011– Teaching Programming, a possible methodology—Marlene Galea

Keyboard Input using Scanner class

1. Import scanner utility

2. Create a Scanner object

3. Read data from keyboard into variables

Final Variables (Constants)

Unary Operators

The Math Class

Importing the Math class: import static java.lang.Math.*;

Methods that return a value

static FINAL int AGE = 5;

import java.util.Scanner;

Type Variable name = new type ();

Scanner input = new Scanner (System.in);

Reading an integer int a = (input.nextInt());

Reading a double variable double a = (input.nextDouble());

Reading a String variable String a = (input.nextLine ());

Operator This is… …equivalent to Operation

++ n++ n = n + 1 Add 1

-- n-- n = n - 1 Subtract 1

+= n+=x n = n + x Addition

Method Description

abs(int x) Returns the absolute value of x

pow(int y, int x) Returns y to the power of x.

sqrt(double x) Returns the square root of x.

random() Returns a pseudo random number between 0 and 1.

public int getArea(){

int area = this.length * this.breadth;

return area;

}

Page 11: Teaching Problem Solving€¦ · Program your robot to move forward until the ultrasonic sensor detects an object within 25cm of it. At this point it should stop. 2. Calibrate your

A simple application that calculates and outputs the details of right-angled triangles

1. Create a class called Triangle that has three properties: a, b and hyp which are sides of a right-angled triangle.

2. In class Triangle, create a method inputDetails() that asks the user to input sides a and b of a triangle.

3. In class Triangle, create a method called findHyp() that given sides a and b, uses Pythagoras’ theorem to find

the hypotenuse (hyp).

4. In class Triangle, create a method called findArea() that given a and b (the base and height) finds and outputs

the area of the triangle.

5. In class Triangle, create a method outputTriangle() that outputs triangle details including: side a, b, hyp and

area.

6. Create a class TriangleApp with a main method that creates an instance of class Triangle and then calls the

relevant methods to:

• Ask the user to input sides a and b of the triangle

• Output triangle details on the screen: including hyp and area.

Changing the size of triangles

7. In class Triangle create a method called makeBigger() that uses the unary operator (++) to increase a and b by

one and then outputs the new dimensions.

Use escape characters to improve the presentation of your output.

8. In class Triangle create a method called makeSmaller() that uses the unary operator (--) to decrease a and b by

one and then outputs the new dimensions.

Use escape characters to improve the presentation of your output.

9. Insert a call to these methods from your main method.

Triangle costings

10. Taking the cost of plastic to be a constant 2.5 Euro, in class Triangle, create a method getCost() that finds and

returns the cost of making the triangle passed to it out of a plastic frame.

11. Taking the VAT Rate to be a constant 18%, in class Triangle, create a method called getVATCost() that finds and

returns the cost of a plastic frame, VAT included.

Basic Level

Advanced Level

Expert Level

Inset September 2011– Teaching Programming, a possible methodology—Marlene Galea

Page 12: Teaching Problem Solving€¦ · Program your robot to move forward until the ultrasonic sensor detects an object within 25cm of it. At this point it should stop. 2. Calibrate your

Inset September 2011– Teaching Programming, a possible methodology—Marlene Galea

Decisions

If..else Case/Switch

For loops

Arrays

Declaring and using an array

Array of Objects

Declaring and using an array of objects

if (mark == 100){

System.out.println ("Well Done");

}

else {

System.out.println ("Not full marks"); }

switch (expression){ case 1: { statement/s; break; } case 2: { statement/s; break; } default: { statement/s; }

}

for ( initialization ; condition ; iteration )

for ( i = 0 ; i<10 ; i++ )

for (x=1; x<=10; x++) {

System.out.println("x=" +x);

}

array-variable = new type [size];

int[ ] marks = new int [5];

for (i=0;i<5;i++){

System.out.print ("Enter mark: ");

this.mark[i] = (input.nextInt());

}

Teacher [] TeacherList = new Teacher[5];

for (int i = 0; i<5; i++){

TeacherList[i] = new Teacher ();

System.out.println();

TeacherList[i].inTeacher();

}

Page 13: Teaching Problem Solving€¦ · Program your robot to move forward until the ultrasonic sensor detects an object within 25cm of it. At this point it should stop. 2. Calibrate your

Inset September 2011– Teaching Programming, a possible methodology—Marlene Galea

An application handling athlete record times for the 100m race

1. Create class Athlete with properties: name, surname, best100m (where best100m is an array containing 10 ath-

lete’s time records).

2. In class Athlete, create a method enterAthlete() that reads the athlete details into the relevant instance variables.

3. Create a class AthleticsApp with a main method which includes the following Menu or else calls a method main-

Menu(). The main menu should display the following options:

1. Enter Athlete 2. View Athlete Statistics 3. Get Team Statistics 4. Exit

4. Implement the main menu such that when the user makes a choice, the system outputs a message saying which

option was chosen.

5. The above should loop until the Exit Option (4) is chosen.

Making our application capable of producing athlete statistics

6. In class Athlete, create a method getStatistics() that outputs:

• An Athlete’s Average

• An Athlete’s Highest personal best (the shortest time)

• An Athlete’s personal best (the longest time)

7. Implement the main menu such that when options 1 and 2 are chosen the relevant method is called.

Editing our application to handle Athletics Teams

8. Change the menu to the following:

1. Create Team 2. Add Athlete In Team 3. View Athletes' Details 4. Get Team Statistics 5. Exit

9. Create a class called AthleticsTeam with instance variables: shortest100m and average.

10. In class AthleticsTeam , declare an array of objects containing 10 athletes.

11. Implement a method getTeamStats() that will output the shortest personal best of all the team and also the aver-

age personal best of all athletes.

12. Make sure the correct method is being called by ALL your main menu options.

Basic Level

Advanced Level

Expert Level

Page 14: Teaching Problem Solving€¦ · Program your robot to move forward until the ultrasonic sensor detects an object within 25cm of it. At this point it should stop. 2. Calibrate your

Inset September 2011– Teaching Programming, a possible methodology—Marlene Galea

Introducing GUI Elements

1. Import the JOPtionPane class

2. Creating a Message Dialog box

3. Creating an Input Dialog box

File Handling 1. Import the necessary file reading and writing classes

2. Create a file object and associate it with a file name

Writing to a file

1. Initialise an object to write lines to a file.

2. Writing a line to a text file

Reading from a file

1. Initialise an object to read lines from a file.

2. Reading a line of text from a text file.

Exception handling

import javax.swing.JOptionPane;

JOptionPane.showMessageDialog(null, “Game Over”);

choices = JOptionPane.showInputDialog( "1. Try Test\n"+ "2. Get Grade and Rank\n"+ "3. Quit\n"+ "Enter choice: \n"); choice = Integer.parseInt(choices);

import java.io.*;

File test = new File("test.txt");

BufferedWriter writer = new BufferedWriter(new FileWriter(test, true));

writer.write(Test[i].question);

writer.newLine();

BufferedReader reader = new BufferedReader(new FileReader(test));

Test[i].question=(reader.readLine());

public static void main (String args[])throws IOException {

Page 15: Teaching Problem Solving€¦ · Program your robot to move forward until the ultrasonic sensor detects an object within 25cm of it. At this point it should stop. 2. Calibrate your

Inset September 2011– Teaching Programming, a possible methodology—Marlene Galea

String handling

Do...while:

The do..while loop is a conditional loop that can depend on 1 or more conditions.

Here while i<4 and string smallGuess is not the same as the string word, the loop will be executed again.

Convert a String to an integer

The following line converts a string (choices) to an integer (choice):

This is useful when using an Input Dialog if we would like to convert the user’s choice to an integer:

String.length();

Returns the number of characters in this string

Returns an integer

int letters = password.length();

String.toLowerCase()

Returns a new string with all characters converted to lowercase

Returns a String

String smalls = password.toLowerCase();

String.equals(String);

Returns true if string is equal to another string

Returns Boolean

guessed = password.equals(pword);

String.charAt(index:int);

returns the character at the specified index from this string

Returns a String

char character = password.charAt(4);

do{

[statement/s]

}while ((i < 4) && (!smallGuess.equals(word)));

String choices; choices = JOptionPane.showInputDialog( "MAIN MENU\n"+ "1. Create New Test\n"+ "2. Try Test\n"+ "3. Get Grade and Rank\n"+ "4. View Answers\n" + "5. Read Notes\n" + "6. Quit\n"+ "Enter choice: \n");

choice = Integer.parseInt(choices);

choice = Integer.parseInt(choices);

Page 16: Teaching Problem Solving€¦ · Program your robot to move forward until the ultrasonic sensor detects an object within 25cm of it. At this point it should stop. 2. Calibrate your

A Simple ‘Guess the Word’ Game that gives the user some help and 3 chances to guess

1. Create class Game that has a single attribute: a file called ‘wordlist’.

2. In class Game create a method enterWords() that allows the user to input 10 words and then stores each of

them into a text file.

3. In class Game create a method getWord() that reads a random word from the text file into a string variable

called ‘word’.

4. In class Game create a method playGame() that:

• calls the method getWord()

• gives the first letter of the word

• gives the number of letters in the word

• Implements a loop to give the user 3 chances to guess the word.

5. In class Game create method runGame() that repeatedly displays a menu with the following options until the

option to quit is chosen:

1. Enter Words 2. Play Game 3. Exit

Implement the main menu such that each option takes execution to the relevant method.

6. Implement a class GameApp with a main method that creates an object of Game and then calls the method

runGame for that object.

Making our game more attractive

7. Edit your method playGame() such that if the word is not immediately guessed, it gives one more letter in the

word at every loop.

8. Make your guessing game caseproof.

9. Implement the above game using GUI elements for:

• The Main Menu

• The message to the user telling him he has guessed the word.

Introducing levels into our game

10. Implement levels in your game such that an easy level would give the user a clue to help him guess the word.

Basic Level

Advanced Level

Expert Level

Teaching Programming, a possible methodology—Marlene Galea