Download presentation
Presentation is loading. Please wait.
Published byMoshe Hadsall Modified over 10 years ago
1
Starting to program with BlueJ and the Beetle - a 2 day course for real beginners Lynda Thomas ltt@aber.ac.uk
2
Introducing ourselves We 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?
3
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 01/09/2014
4
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 something Selection: if something then do one thing if not do something else Mainly by using a ‘Beetle’ that responds to commands
5
Why are we starting this way? We want you to get going quickly with programming Seeing 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!!!
6
Where do we start? (let’s do this now) Logging on Open a browser Accessing the department’s web site http://www.aber.ac.uk/compsci Then pick Current Students, Then Teaching The pick Module Information Notes 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
7
PROGRAMMING
8
What is programming? Telling the computer to ‘do’ something You write instructions in a language that you understand The instructions are then translated into something the ‘computer’ understands That is then run The writing is - programming (writing code) The translating is - compiling (sometimes interpreting) The running is - executing (running)
9
Some examples Web page Written in html Every time a browser looks at it, it is translated The equivalent of running would be the displaying The program that UCAS uses to process admissions Written in a programming language Translated into something that runs Run to accept input from AU and produce notifications What we are doing today Written in Java (but have some ‘magic’ so could be C) Translated into something that runs in BlueJ Run to make a little Beetle draw on the screen
10
BASIC BLUEJ BlueJ 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
01/09/2014 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
12
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) 01/09/2014 You may need to click compile first
13
Here you see what then happens when I run that method 01/09/2014 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 distance THIS IS WHAT WE CARE ABOUT HERE
14
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 project Click compile Right click on the Test class and pick its main method Make sure you get the same result as me If NO HAND UP If YES TRY CHANGING THE DISTANCE compile and run again
15
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); } 01/09/2014
16
Some things to notice The top bit of code between /** and */ is a comment Comments are there for people reading the code You can put anything you like in them For instance put your name in instead of mine Compile again Run again Programming languages are really fussy the { and the } must match up You must spell ‘bob’ consistently Try changing one to Bob for instance, try compiling 01/09/2014
17
How is this working? All BlueJ gives us is the framework for programming I have written the code (in beetlemechanics) that actually makes the Beetle appear and draw You will be using that code in the main method of the Test class to do things by: Typing in new code Compiling it Running the main method 01/09/2014
18
What can this BJBeetle thing do? Pick Documentation from the Tools menu (Ctrl+J) ORDouble click on the BJBeetle class Pick Documentation on the top right (if need to) Scroll down a bit and you will see the list of things 01/09/2014 CHECK–coming out funny on my machine On handout also
19
So, actually here we have created 2 BJBeetle objects and got them to draw some shapes 01/09/2014 The object bench is a picture of what the memory of the computer looks like TRY IT!! – CODE IS IN draw-Basic.txt
20
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 parameters Some methods have no parameters, some one, some many
21
Exercise 1 (let’s do this now) In your main method of the Test class create a couple of BJBeetles Use several of the methods in turn and see what happens as you move the Beetles around Most 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
22
Have you completed exercise 1? Created a BJBeetle object Made it do a couple of methods Seen the documentation Can find a method with 4 parameters Please help me! 01/09/2014
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 them The convention is to use lower case letters to start variable names
24
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
25
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
26
Exercise 2 (let’s do this now) Create a new class called Test2 by clicking on New Class button Remove all its code and replace with the code from the Test class Change 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
27
Have you completed exercise 2? Created a BJBeetle object Drawn a T Please help me! 01/09/2014
28
A bit more about variables Not all variables represent objects like BJBeetle, some are ‘primitive’: int holds a whole number double 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;
29
Think of the variable as a place in the memory of the computer that values can go in int variables can hold ints double variables can hold doubles String variables can hold Strings BJBeetle variables can hold whole Beetles 01/09/2014
30
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; 01/09/2014 19 20 age
31
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 …
33
Things to note: System.out.println() prints stuff in the terminal window So, 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’
34
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);
35
Have you completed exercise 3? Created some primitive variables Changed their values (try +,-,*,/) Printed out values Please help me! > 01/09/2014
36
LOOPS
37
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
38
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
39
What happened when you tried it?
40
What is happening behind the scenes? for (int counter=0;counter<5;counter++) { System.out.println(“hi”); } This is the loop header Controls the loop with the counter variable This (between the { and the } is the loop body Gets repeated over and over
41
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
42
The loop body Starts with a{ Ends with a} Everything between is the body which gets repeated.
43
How do you design a for loop? Figure out how many times you want to do something – that is your loop control Figure 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 +”: “); } 01/09/2014
44
Exercise 4 (let’s do this now) Paste the code star.txt into a class as the ‘main code’ like before and try it Modify 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?)
45
Have you completed exercise 4? Drawn one 5 pointed star Drawn one 7 pointed star Drawn 4 stars Please help me! 01/09/2014
46
End of teaching day 1
47
Review Used BlueJ to play with some code Created 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++) { } 01/09/2014
48
Have you completed exercise 4? Drawn one 5 pointed star Drawn one 7 pointed star Drawn 4 stars Please help me! 01/09/2014
49
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
50
IF s (also input)
51
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
52
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
53
Input There is a new class called InputGetter that grabs a String from the user It has 3 methods
54
Exercise 5 - Try this code in a new class InputGetter 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
55
The getInputFromUser() method asks for input 01/09/2014
56
The getInputFromUser(String message) method asks for input but with a message – note these methods have the same name but different parameters needed 01/09/2014
57
The getCurrentValue() method ‘returns’ a value that can be manipulated or printed 01/09/2014
58
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
59
Have you completed exercise 5? Tested the code to get input and print that input Please help me! 01/09/2014
60
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"); }
61
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
62
This is what happened when I typed in my name Try typing in bill and fred yourself 01/09/2014
63
Exercise 6 - Try this code in a new class It 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
64
Have you completed exercise 6? Tested the code to get input and print different things depending on that input Please help me! 01/09/2014
65
Conditions – True or False Comparing 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 ints String s=reader1.getCurrentValue(); int number=Integer.parseInt(s);
66
Nesting control structures
67
Now look at zzNesting.txt Here we have the idea that you can ‘nest’ control structures LOOP{ code IF { …. }
68
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"); } 01/09/2014 Try it!! – zzNesting.txt - note no error checking } Loop } If
69
01/09/2014
70
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) >
71
Have you completed exercise 7? Loop through some people Ask if over 18 Print iechyd da if they say yes 01/09/2014
72
Note you are ‘nesting’ an IF in a LOOP You can ‘nest’ all control structures! Note ‘comments’ Already nested loops yesterday when we drew 4 stars BJBeetle 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); }
73
You can nest control structures to any depth for (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 (…) { } } if (…) { //one possibility is break out of the loop } }
74
So you can have an if in a loop or a loop in an if or a loop in an if in a loop The 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 Brown Ms. Mary Smithetc. appropriately
75
Loop through 10 students process a student Now how process just one student? (ie do the body of the loop) 01/09/2014 Or you could do this in the other order ie 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:
76
Be sure to sort out indentation properly 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); }
77
Then make refinements like I did Lots of other possibilities Any number of students, first read number, then for (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); } 01/09/2014
78
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”); >
79
Structure is 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 01/09/2014
80
Have you completed exercise 8? Recognises your initials Drawn the circle if asked for Or draws the star if asked for Please help me! 01/09/2014
81
End of teaching day 2
82
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? > What do you want to do? > Goodbye! That means you will have to have designed code for your UID. (Start by just recognising your user id.)
83
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 goodbye 01/09/2014
84
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 - LOOP Have a basic understanding of Selection - IF Mainly by using a ‘Beetle’ that responds to commands
85
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! 01/09/2014
86
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 variable bob.moveForward(100);//making if do something //with an argument There are some things called variables, loops and if statements 01/09/2014
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.