starting to program with bluej and the beetle - a 2 day course for real beginners lynda thomas...

Post on 31-Mar-2015

215 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Starting to program with BlueJ and the Beetle - a 2 day course for real beginners

Lynda Thomasltt@aber.ac.uk

Introducing ourselvesWe are …Introduce yourself to your neighbours

Where are you from?Why you chose the degree scheme you’re

enrolled on?How much (if any) programming have you

done before?What interests you about computing?

Which of the following have you done before? (Choose all that apply)

Used Word or … Made a web site Built a database application Written program in a programming

language None of the above

11/04/23

What should you be able to do at the end of this week (with some help)?

Use the BlueJ IDE (Integrated Development Environment). This is a way beginners can write programs

Have a basic understanding of Iteration: lots of times do somethingSelection: if something then do one thing

if not do something else

Mainly by using a ‘Beetle’ that responds to commands

Why are we starting this way?We want you to get going quickly with

programmingSeeing how things work and

Building things are what computing is all about

It is fun (if a bit frustrating at times)It gives you a sense of accomplishment, and

It takes PRACTICE!!!

Where do we start? (let’s do this now)Logging onOpen a browserAccessing the department’s web sitehttp://www.aber.ac.uk/compsciThen pick Current Students, Then TeachingThe pick Module InformationNotes are at either:

Blackboard, or Dept’s Web site

Materials for just these 2 days are on the Department’s web site under a-two-day-introduction-beginners

PROGRAMMING

What is programming?

Telling the computer to ‘do’ somethingYou write instructions in a language that you

understandThe instructions are then translated into

something the ‘computer’ understandsThat is then run

The writing is - programming (writing code)The translating is - compiling (sometimes interpreting)The running is - executing (running)

Some examplesWeb page

Written in htmlEvery time a browser looks at it, it is translatedThe equivalent of running would be the displaying

The program that UCAS uses to process admissionsWritten in a programming languageTranslated into something that runsRun to accept input from AU and produce

notificationsWhat we are doing today

Written in Java (but have some ‘magic’ so could be C)

Translated into something that runs in BlueJRun to make a little Beetle draw on the screen

BASIC BLUEJBlueJ is the environment in which we will be

writing, translating and running our programs – it is actually created for the Java programming language – but we are using a

fairly language neutral part of it because it is easy

11/04/23

This is what BlueJ looks like.

We are going to be creating BJBeetle-y kinds of things – you can think of them as little robots you can control that draw as they move. They will be tested in some code called Test

Ignore these two things for now

Here you see me, having right clicked on Test, about to pick a method (piece of code) called main(you also see the code for that method)

11/04/23You may need to click compile first

Here you see what then happens when I run that method

11/04/23

Read the 2 lines of code between the public static void main …. and the}

}and compare them with the result

They create a new BJBeetle thing and make it move forward a distanceTHIS IS WHAT WE CARE ABOUT HERE

Exercise 0 (let’s do this now)Download Beetle.zip from web site (right click)/

Unzip it (right click and pick extract) and put it in a new directory on your m: drive

Now run BlueJ you will find it under the start button All Programs/ Courseware/ Computer Science

Open the BeetleWithInput projectClick compileRight click on the Test class and pick its main methodMake sure you get the same result as me

If NO HAND UPIf YES TRY CHANGING THE DISTANCE

compile and run again

We will be ignoring some bits of the code for now

The bit we care about is in red/** * This class is the 'automagic' in which we will build our programs * * @author (Lynda Thomas) * @version (a version number or a date) */public class Test{ public static void main(String args[]) { BJBeetle bob=new BJBeetle(); bob.moveForward(100); }}

11/04/23

Some things to notice

The top bit of code between /** and */ is a commentComments are there for people reading the codeYou can put anything you like in themFor instance put your name in instead of mine

Compile again Run again

Programming languages are really fussy the { and the } must match upYou must spell ‘bob’ consistently

Try changing one to Bob for instance, try compiling11/04/23

How is this working?All BlueJ gives us is the framework for programmingI have written the code (in beetlemechanics) that

actually makes the Beetle appear and drawYou will be using that code in the main method of

the Test class to do things by:Typing in new codeCompiling itRunning the main method

11/04/23

What can this BJBeetle thing do?Pick Documentation from the Tools menu (Ctrl+J)

OR Double click on the BJBeetle classPick Documentation on the top right (if need to)Scroll down a bit and you will see the list of things

11/04/23

CHECK–coming out funny on my machine

On handout also

So, actually here we have created 2 BJBeetle objects and got them to draw some shapes

11/04/23

The object bench is a picture of what the memory of the computer looks like

TRY IT!! – CODE IS IN draw-Basic.txt

Arguments / Parameters

The values that you put in parentheses when you ‘call’ a method are called arguments. When you moveForward(100) the 100 is the argument.So we ‘pass in’ the argument to the method

But you need a way to talk about the value that is moved forward in a general way. The Beetle moves forward by a ‘distance’. In the context of the method moveBackward, distance is called a parameter

The arguments then, get copied into the parametersSome methods have no parameters, some one, some many

Exercise 1 (let’s do this now)In your main method of the Test class create a couple of

BJBeetlesUse several of the methods in turn and see what

happens as you move the Beetles aroundMost of the methods will need arguments

(colours are typed in as java.awt.Color.red etc.)Can you find a method with 4 parameters? Test it

Have you completed exercise 1?

Created a BJBeetle objectMade it do a couple of

methodsSeen the documentationCan find a method with 4

parametersPlease help me!

11/04/23

We have to talk about variable names

Variables are names we give to pieces of computer storage/memory so we can manipulate them.

We have seen variables already, bob and fred were variables that are of the type BJBeetle

Variable names must not have spaces in themThe convention is to use lower case letters to start

variable names

Parameters are also variable names

parameters - these are ones that accept the arguments when we call a method bob.turn(45); public void turn(int degrees) {}

degrees is a parameter variable name - needed so

that in the code for the turn method you can use that instead of ‘45’ or ‘90’ or whatever is currently being asked for

You need something generic to talk about

The idea that we use names to stand in for values is essential to programming

You can guess that when we tell bob to turn(45) what happens is that the little Beetle ‘s picture is turned by that number of degrees.

When we tell it to moveForward(100) it moves forward by that distance

So we can express what happens generically as an ‘algorithm’ or set of instructions using ‘degrees’ and ‘distance’ to describe the general instructions

Exercise 2 (let’s do this now)Create a new class called Test2 by

clicking on New Class buttonRemove all its code and replace with the

code from the Test classChange the line that says

‘public class Test’ to ‘public class Test2’The names must match

Make this picture by writing code in the main method of Test2

To reformat code and indent prettily hit Ctrl+Shift+I or pick Edit-Auto Layout

Have you completed exercise 2?

Created a BJBeetle objectDrawn a TPlease help me!

11/04/23

A bit more about variablesNot all variables represent objects like BJBeetle, some are ‘primitive’:int holds a whole numberdouble holds a number with a decimal point boolean is true or false

String is not primitive but it is very simple

These kinds of variables are created without saying ‘new’. You just say String name="fred"; int age=19;

Think of the variable as a place in the memory of the computer that values can go inint variables can hold intsdouble variables can hold doublesString variables can hold StringsBJBeetle variables can hold whole Beetles

11/04/23

When you declare the variable you say you need one of that kind

Then you can put different values in it as the program runs

int age;

age=19;

age=20;

11/04/23

19

20

age

Exercise 2 (let’s do this now)Create a new class and put this in the main method:

int age=19;

double hourlyWage=4.5;

boolean penUp=false;

String name="fred";

age++;

hourlyWage=hourlyWage*2;

System.out.println(name+" is "+age+” and makes “+ hourlyWage);

Then compile and run it – code is in output.txt but …

Things to note:

System.out.println() prints stuff in the terminal windowSo, up pops the Terminal window and the values of the variables are printed (along with explaining text that you determine)

The + comes between things you want to print in a prinln to link them

Notice how ++ adds 1 to an int variable (so does +1), and *2 multiplies by 2

Notice also how the quotes and ()s need to match

To clear the Terminal window pick Options-clear

This is a lower case ‘L’For ‘line’

What is happening?

Declares these variables, says what kinds of things they are

allowed to hold, and puts some initial values in

Changes values

Prints values

int age=19;

double hourlyWage=4.5;

String name="fred";

age++;

hourlyWage=hourlyWage*2;

System.out.println(name+" is "+age+” and makes “+ hourlyWage);

Have you completed exercise 3?

Created some primitive variables

Changed their values (try +,-,*,/)Printed out valuesPlease help me!

<<end of session 1>>

11/04/23

LOOPS

OK, now the first of our ‘control structures’ At the moment our code just runs one

line, then the next etc. Often we want to do the same thing

over and over (for instance printing an invoice of items, a list of students etc)

Called ‘iteration’ There are several different ways of

doing iteration – the loops. We will look at one

The ‘counted for loop’ Does something a certain number of times Looks like this example:

for (int counter=0;counter<5;counter++) {System.out.println(“hi ”+counter);

}Try it now in a new class

What happened when you tried it?

What is happening behind the scenes?

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

System.out.println(“hi”);

}

This is the loop headerControls the loop with the

counter variable

This (between the { and the }is the loop body

Gets repeated over and over

The loop header

for (int counter=0; counter<5; counter++)

Says what kind of loop

This starts up a variable called counter with value 0(the variable can have any

name)

Do the loop while the counter is less than 5

Every time you go through the loop add

one to counter – after doing body

The loop body

Starts with a {

Ends with a }

Everything between is the body which gets repeated.

How do you design a for loop?Figure out how many times you want to do

something – that is your loop controlFigure out what you want to do over and over – that

is your loop body.Sometimes the control is used in the body:

for (int count=0;count<30; count++) {System.out.println(“Student “+ count +”: “);

}

11/04/23

Exercise 4 (let’s do this now)Paste the code star.txt into a class as the

‘main code’ like before and try itModify it to draw a 7 pointed star

(the angle you need is 720/number of sides)

Now can you draw 4 stars? What about 10 stars?

(hint: What do you need to do between drawing each star?)

Have you completed exercise 4?

Drawn one 5 pointed starDrawn one 7 pointed starDrawn 4 starsPlease help me!

11/04/23

End of teaching day 1

ReviewUsed BlueJ to play with some codeCreated several objects

BJbeetle bob=new BJBeetle(); Called the methods for those objects this involved

passing arguments into the methods – like bob.turn(90);

Done some output like System.out.println(“hi”+name);Looked at loops like

for (int counter=0;counter<10;counter++) {

}

11/04/23

Have you completed exercise 4?

Drawn one 5 pointed starDrawn one 7 pointed starDrawn 4 starsPlease help me!

11/04/23

What should you be able to do at the end of this week (with some help)?Use the BlueJ IDE Have a basic understanding of Iteration

Have a basic understanding of Selection: if something then do one thing

if not do something else

Mainly by using a ‘Beetle’ that responds to commands

IF s(also input)

OK, now the second of our ‘control structures’

At first, our code just ran one line, then the next etc.

But now we have seen iteration (doing something over and over)

Sometimes we want to do one thing in one case and something different in another

This is called ‘selection’ We will look at the ‘if’ statement

The ‘if’ statement Does different things in different situations For instance, BJBeetle objects draw if the pen

is down and don’t otherwise

But that means our code usually needs some input to get a different situation

So, first let’s get some input into the program to create different situations

Input There is a new class called InputGetter that

grabs a String from the user It has 3 methods

Exercise 5 - Try this code in a new classInputGetter input=new InputGetter();input.getInputFromUser();System.out.println("you typed "+input.getCurrentValue());

Creates an InputGetter thing and then asks user to type something, prints it back for them

Most of this is not of interest but look at ‘str’ which holds what I typed

The getInputFromUser() method asks for input

11/04/23

The getInputFromUser(String message) method asks for input but with a message – note these methods have the same name but different parameters needed

11/04/23

The getCurrentValue() method ‘returns’ a value that can be manipulated or printed

11/04/23

Returning values from a method This is sort of the opposite of passing a value

into a method through argument/parameter this method produces a value that can then be

used – in this case a String Look at the documentation for these methods

Have you completed exercise 5?

Tested the code to get input and print that input

Please help me!

11/04/23

The ‘if’ statement Does different things in different situations Looks like this example:InputGetter reader=new InputGetter();reader.getInputFromUser();String name=reader.getCurrentValue();if (name.equals("fred")) {

System.out.println("found fred");}else { System.out.println("not Fred");}

What is actually happening?

if (name.equals("fred")) {System.out.println("found fred");

}else { System.out.println("not Fred");}

This is where we test the condition – must be true or false

If true do this

If false do this

This is what happened when I typed in my name

Try typing in bill and fred yourself

11/04/23

Exercise 6 - Try this code in a new classIt is in testif.txt

InputGetter reader=new InputGetter();reader.getInputFromUser();String name=reader.getCurrentValue();if (name.equals("fred")) {

System.out.println("found fred");}else { System.out.println("not Fred");}

What happens when you type in various things? Bill, fred, Fred, 1234, ^%$&^%

Most of this is not of interest but look at ‘str’ which holds what I typed

Have you completed exercise 6?

Tested the code to get input and print different things depending on that input

Please help me!

11/04/23

Conditions – True or FalseComparing Strings – String name;

if (name.equals(“Fred”)) if (!(name.equals(“Fred”))) //note ‘NOT’ is written ‘!’

Comparing numbers – int age; if (age==18) //note ‘is equal to’ if (age!= 5) //note NOT if (age>=65) //note ‘is greater than or equal’ If (age<40) //note ‘is less than’

a clever way of turning Strings to intsString s=reader1.getCurrentValue();int number=Integer.parseInt(s);

Nesting control structures

Now look at zzNesting.txt

Here we have the idea that you can ‘nest’ control structures

LOOP{codecodeIF {

….}

}

public static void main(String args[]) {

InputGetter reader1=new InputGetter();

InputGetter reader2=new InputGetter();

InputGetter reader3=new InputGetter();

reader1.getInputFromUser("how many people do you have");

String s=reader1.getCurrentValue();

int number=Integer.parseInt(s); //a clever way of turning Strings to ints

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

reader2.getInputFromUser("enter your name");

reader3.getInputFromUser("enter male or female");

String name=reader2.getCurrentValue();

String gender=reader3.getCurrentValue();

if (gender.equals("male")) {

System.out.println("Mr. "+name);

}

else {

System.out.println("Ms. "+name);

}

}

System.out.println("Thanks you for using my program");

}

11/04/23Try it!! – zzNesting.txt - note no error checking

}Loop}If

11/04/23

Exercise 7 (let’s do this now)Write come code with a loop and an if statement

that Asks someone whether they are over 18. If they say “yes” print “iechyd da”, if not print

“have a coke”

(you can use the zzNesting.txt as a pattern)

<<end of session 3>>

Have you completed exercise 7?

Loop through some peopleAsk if over 18Print iechyd da if they say

yes

11/04/23

Note you are ‘nesting’ an IF in a LOOPYou can ‘nest’ all control structures! Note ‘comments’

Already nested loops yesterday when we drew 4 starsBJBeetle bob=new BJBeetle();

//four times

for (int counter=0;counter<4;counter++) {

//draw a star this also involves a loop

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

bob.turn (720/5);

bob.moveForward(70);

}

bob.setPenUp(true); bob.moveForward(100); bob.setPenUp(false);

}

You can nest control structures to any depthfor (int i=0;i<4;i++) { for (int j=0;j<3;j++){ System.out.println

(i+" "+j);}

}

if (age<3) { System.out.println("play at home");}else if (age<6) { System.out.println("at nursery");}else if (age<13) { System.out.println("play outside!");}else if (age<18) { System.out.println("no - I won't give you

any money");}else { System.out.println("you are on your own

love");}

if (something) {for (…) {}

}

for (…) {if (…) {

//one possibility is break out of the loop}

}

So you can have an if in a loop or a loop in an ifor a loop in an if in a loopThe trick is to figure out ‘in words’ what you want to do and only actually code just a bit at a time:

I wanted to ask some students their names and genders and print something like:

Mr. John BrownMs. Mary Smith etc.

appropriately

Loop through 10 students process a student

Now how process just one student? (ie do the body of the loop)

11/04/23

Or you could do this in the other orderie first how do one student and then stick a loop around it for lots of students!

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

//process a student}

String name=reader1.getCurrentValue();

String gender=reader2.getCurrentValue();

if (gender.equals("male")) {

System.out.println("Mr. "+name);

}

else {

System.out.println("Ms. "+name);

}

First think about the overall structure:

Be sure to sort out indentation properly

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

//process a studentString name=reader1.getCurrentValue();

String gender=reader2.getCurrentValue();

if (gender.equals("male")) {

System.out.println("Mr. "+name);

}

else {

System.out.println("Ms. "+name);

}

}

Then make refinements like I didLots of other possibilities

Any number of students, first read number, thenfor (int i=0; i<number; i++) {

Could also check for bad input: String s=reader1.getCurrentValue();

int number=5; //back up if (s.equals(“”)) { //so nothing read

System.out.println(“doing it 5 times”);

} else{

number=Integer.parseInt(s); }

11/04/23

Exercise 8 (let’s start these now)Modify the code for testif.txt so it recognises

your User ID when you input it and outputs a suitable message.

Then modify so if you input “circle” a BJBeetle draws a circle.

And if you input “star” a BJBeetle draws a star If none of above it prints “sorry – do not

understand”);

<<you can find the code for a circle in zzCircle.txt>>

Structure isask for input

if your uid

draw it

else if circle

draw circle (this involves a loop)

else if star

draw star (this involves a loop)

else Say sorry

11/04/23

Have you completed exercise 8?

Recognises your initialsDrawn the circle if asked forOr draws the star if asked

forPlease help me!

11/04/23

End of teaching day 2

Want more practice?Modify the code you produced in Exercise 8 so that your program runs like this (putting a loop around Exercise 8 code):

How many times to run? <<you type in, say 5>>What do you want to do? <<you type in star it draws one>>What do you want to do? <<you type in circle it draws one>>What do you want to do? <<you type in circle it draws one>>What do you want to do? <<you type in your UID it draws it>>What do you want to do? <<you type in other word it says ‘sorry’>>

Goodbye!

That means you will have to have designed code for your UID. (Start by just recognising your user id.)

This means you will have a structure like:

Ask for number of times

loop that many times

ask for input

if your uid

draw it

else if circle

draw circle (this involves a loop)

else if star

draw star (this involves a loop)

else Say sorry

Say goodbye11/04/23

What should you be able to do at the end of this week (with some help)?Use the BlueJ IDE Have a basic understanding of Iteration -

LOOPHave a basic understanding of Selection - IF

Mainly by using a ‘Beetle’ that responds to commands

What next?Do you notice how it is getting a bit mammoth in the

main method?We need to break up our code into parts!

11/04/23

Aaaaargh! I am feeling a bit lost!!!!

If this describes you We will be going over all this again in CS12020, so don’t panic!We hope that this brief introduction will have given you some experience that you can bring into the course.If only this much:

BJBeetle bob=new BJBeetle(); //creating an object as a variablebob.moveForward(100); //making if do something

//with an argument

There are some things called variables, loops and if statements

11/04/23

top related