Java Course 4: Selection

if statement

Scanner scan = new Scanner(System.in); 
System.out.println("How old are you?"); 
int age = scan.nextInt(); 
if (age < 18) { 
            System.out.println("You're too young to vote"); 
} else { 
            System.out.println("You're old enough to vote"); 
}

Operators

  • <, >, <=, >=
  • .equals() (for Strings)
  • .equalsIgnoreCase()
  • ! not
  • | or
  • & and

Examples

  • if (age>10 & age<19)
  • if(surname.equals(“Ballantyne”))
  • if(surname.equalsIgnoreCase(“Ballantyne”))
  • if(!answer.equals(“quit”))

Questions

Don’t forget to paste your code beneath the questions!

  1. Write a program that asks a user to input their BMI (body mass index) and then outputs their BMI Category as follows: Underweight = <18.5, Normal weight = 18.5–24.9, Overweight = 25–29.9, Obesity = BMI of 30 or greater
  2. Ask the user to input the name and age of two people. e.g. George, 32, Jill, 35. Get it to print out who is the youngest/oldest e.g. George is younger than Jill
  3. Honorific Generator: Write a program that accepts as input a person’s sex and age, and outputs the honorific Mr, Ms, Miss or Master
  4. Days in the month: Input the name of the month and whether or not it’s a leap year, then output the number of days in that month
  5. Write a quiz with 2 questions. Print out the users score out of 2 at the end of the quiz
  6. Write a password checker. Give the user three chances to enter the correct password.

Extension

  1. Personality test: Look at the personality test here http://www.personalityquiz.net/profiles/typology/index.htm Write a program that replicates this test.
  2. Allow the user to input a number. Output if the number is odd or even
  3. Search for the java switch case statement. Rewrite the last question using switch case.

Python Course 1: Turtle Graphics

Useful Code

Moving the Turtle

turtle.forward(100)
turtle.back(50)
turtle.right(90)
turtle.left(45)
turtle.goto(10,10)
turtle.home()
turtle.setheading(0)

Changing the Pen

turtle.pencolor('red')
turtle.penup()
turtle.pendown()
turtle.pensize(4)

Changing the Board

turtle.reset()
turtle.bgcolor('blue')
turtle.showturtle()
turtle.hideturtle()

Exercise

Draw the following

  1. A square with sides of length 100
  2. An equilateral triangle with sides of length 80
  3. A noughts and crosses board
  4. Draw a star by turning an angle of 144 degrees.
  5. A red hexagon on a blue background.

Lesson 2

The following program draws a purple square with a black border. Note the use of begin_fill() and end_fill()

import turtle

turtle.fillcolor('purple')
turtle.pencolor('black')

turtle.begin_fill()
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.end_fill()

The above requires a lot of cut and paste code: always a sign that there is a better way of doing things. Here’s one way:

import turtle

turtle.fillcolor('purple')
turtle.pencolor('black')

turtle.begin_fill()

for times in range(4):
    turtle.forward(100)
    turtle.left(90)

turtle.end_fill()

We are going to be drawing lots of squares. We can define the  code to draw a square as a function, that way we can reuse it. (Learning  to use functions is the main reason we are using turtle graphics!)

import turtle

def square():
    for times in range(4):
	turtle.forward(100)
	turtle.left(90)

turtle.fillcolor('purple')
turtle.pencolor('black')

turtle.begin_fill()
square()
turtle.end_fill()

We can add a size parameter to the function. Now we can draw squares of different sizes.

import turtle

def square(size):
    for times in range(4):
	turtle.forward(size)
	turtle.left(90)

square(50)
square(100)
square(200)

Exercise

1) Enter the following code and run it. Make sure you understand what it’s doing.

import turtle

def square():
    for times in range(4):
	turtle.forward(100)
	turtle.left(90)

for n in range(8):
    square()
    turtle.right(45)

2) What do you think the following code will do? Enter it and run it.

import turtle

def square(size):
    for times in range(4):
	turtle.forward(size)
	turtle.left(90)

for n in range(8):
    square(20*n)

3) Define a function to draw a triangle.
4) Use your triangle function to draw the following shape

Extension

  1. Write a function to draw a pentagon
  2. Write a function to draw a hexagon
  3. Draw a function that accepts a parameter number_of_sides that draws a  polygon with that number of sides
  4. Write a function to draw a chessboard
  5. Write a function to draw a honeycomb

Todos and Agenda Views

The following post is part of my new Emacs Writing Setup. You can find the complete setup here on GitHub: https://github.com/ballantony/emacs-writing


On my original Emacs Writing Set Up I had this many states:

(setq org-todo-keywords
      (quote ((sequence "TODO(t!)"  "NEXT(n!)" "|" "DONE(d!)")
              (sequence "REPEAT(r)"  "WAIT(w!)"  "|"  "PAUSED(p@/!)" "CANCELLED(c@/!)" )
	      (sequence "IDEA(i!)" "MAYBE(y!)" "STAGED(s!)" "WORKING(k!)" "|" "USED(u!/@)"))))

Now I only have three: TODO, IN PROGRESS and DONE

This is in line with my philosophy that productivity systems are great procrastinators. Thinking of new tagging systems and states for tasks is very absorbing. You can spend hours moving notes around and not doing any work.

Now I capture all my notes as TODOs, I change their state to IN PROGRESS and DONE as projects advance.

Calling org-agenda gives me a bird’s eye view of everything I’m working on. I can then filter down as appropriate.

For convenience, I wrote the following function to restrict the agenda to the current project. ou can see an example in my config.el file

(defun tb/agenda-restrict-this-project ()
    "Restrict agenda to current project"
    (interactive)
    (let ((org-agenda-files (list (projectile-project-root))))
      (org-agenda)))

I rely a lot on this function. When writing I hit SPC j p p (my keybinding: see my config.el file) to see the TODOs and IN PROGRESSes for the current project only.

You can read more in My Doom Emacs Writing Set Up

Capturing and Refiling Notes

The following post is part of my new Emacs Writing Setup. You can find the complete setup here on GitHub: https://github.com/ballantony/emacs-writing

Capturing Notes

Like any writer I’m always capturing ideas. I used to carry a notebook everywhere, now I capture ideas on my phone using either orgzly or Evernote.

When working in Emacs I use org-capture.

GTD means capturing ideas quickly. I used to have templates to capture to different locations, I realised that this was an unnecessary step. Now I either capture everything as a TODO, either directly to my gtd file, or directly to the story file I’m currently working on.

As org-capture requires you to select a template I wrote the following two functions. The first calls org-capture with the ’t’ template preselected, the second does the same but uses let* to change org-capture-templates to the current buffer for the current capture only.

(defun tb/capture ()
    "Capture to do without options"
    (interactive)
    (org-capture nil "t"))

  (defun tb/capture-to-this-buffer ()
    "Capture note to this buffer"
    (interactive)
    (cond  ((not  (eq major-mode 'org-mode))
            (message "Can't capture to non org-mode buffer"))
           (t
            (let* ((this-file buffer-file-name)
                   (org-capture-templates
                    `(("t" "Todo" entry (file+headline ,this-file "Captured")
                       "** TODO %?"))))
              (org-capture)))))

2. Refiling Notes

org-refile makes it easy to refile notes, particularly with a completion system like Vertico. On Doom Emacs this means hitting SPC m r r

Why Doom Emacs?

Way back in September I posted about my new Emacs Writing Set Up: Productivity Overview

Things might have appeared to have gone a little quiet since then. Behind the scenes, however, I’ve been making changes. One of these is to begin the process of moving my Emacs Writing Setup across to GitHub: https://github.com/ballantony/emacs-writing.

I’ll continue to blog relevant content here. Here’s the first, explaining why I’ve adopted Doom Emacs.


Emacs is incredibly configurable. I can choose, for example, the shape and contents of my agenda, the completion engine I use and even such things as the colour of my Todos.

And that’s a problem. Emacs allows me to configure many things that, if I’m honest, I really don’t care about.

It’s very easy to fall into the Emacs trap of sending time configuring the system rather than doing any actual work. I don’t want to think about how many hours I’ve spent experimenting with new packages and thinking of the perfect key bindings when I could have been writing stories instead. GTD can be a powerful procrastinator.

That’s why I’m happy to let someone else do it for me.

Enter Doom Emacs. So what if the TODOs are a different colour to the ones I use, and the capture templates aren’t quite the ones I was using, they’re still good. The key bindings may be different, but they’re far more extensive than any I’ve ever set up and I could probably finish a short story in the time it would take me to replicate them (and I can always override the few I really care about: C-e for example).

Most of all, Henrik Lissner, the creator of Doom Emacs, knows so much more about Emacs than I. I’ve learned so much simply tracking through his code. I wasn’t aware of Vertico until it turned up in the Doom config. I don’t have the time or inclination to try out all new Emacs packages. It’s great that someone else is doing this, and if I don’t like their choices, well, Doom is flexible enough for me to change them.

One final observation. Doom Emacs is fast to load. This is important to me. I like to take notes or begin writing when inspiration strikes. I can open Doom Emacs (or Orgzly on my mobile phone) and take a note in the time it takes apps such as Evernote or Notion to load.

Productivity Overview

My second most popular post ever describes my Emacs Writing Setup. (My most popular post, if you’re interested, is this one.)

I wrote five novels and about thirty short stories using the method described in my Emacs Writing Setup, all the while experimenting with other methods. For example, I replicated some Scrivener features in Emacs and wrote about them here.

But over the past year all this has changed. So much so that I’m rewriting my Emacs Writing Setup from scratch.

So what’s changed? Briefly, I’ve started using org-roam and Doom Emacs for my writing flow. This has had a knock on effect for my productivity flow in general.

I think that I’m a productive person. I’m an assistant head teacher. I’ve had 8 novels and around 70 short stories short stories published. I maintain three blogs. I play jazz piano, accordion and baritone horn and am a member of two bands. Most importantly I’m a husband, carer and father to two children.

My two secrets? I watch very little TV and I rely heavily on productivity systems. I think if you’re not using a system then you’re not meeting your full potential.

The systems I use are GTD and Zettelkasten. I’ve experimented with others, but these are the two that best match my needs and personality.

I’ve also experimented with various software applications over the years. I’ve yet to find one piece of software that meets all my needs, although Emacs comes close. If I were to work solely on a laptop, that’s all I would use, but like most people I also rely on a phone and browser.

Orgzly and beorg do a good job of replicating the Emacs experience on a phone, but Emacs without a proper keyboard is always unsatisfying. And, as yet, I’ve not found a satisfactory way of using Emacs via a browser.

So my current productivity system relies on three ‘applications’

  • Emacs
  • Evernote
  • Notebook and pen (I use Leuchtturm1917 notebooks and Uniball Jetstream pens for preference)

I use Emacs for most things, principally org-mode for writing and org-roam for Zettelkasten

Why do I use Evernote when I have Emacs? Remember, Zettelkasten is a tool for thinking, it’s not a reference tool. One of the principles of Zettelkasten is that you should separate your notes from your reference materials.

Evernote is ideal for reference, it’s also more suited for phone and browser access. The newly added Evernote Tasks feature goes some way to replicating org-agenda. Okay, it’s got a long way to go to match Emacs but I can live with it for the convenience. (I experimented with Todoist for a while before Evernote tasks came out. I liked Todoist so much I almost feel guilty for not using it. It’s an excellent piece of software, but I like to have all my to dos in one place)

Finally, I use a notebook for ideas and thinking things through.

As word documents are the de facto standard in the publishing world , I still use LibreOffice Writer for submissions and editing, but I would say that I spend 99% of my time on Emacs, Evernote and in my Notebook.

This series of posts describe how I use these Emacs, Evernote and my notepad to implement GTD and Zettelkasten, particularly to support my writing process. As I don’t have the patience to watch videos, as I’m not interested in personal anecdotes or dubious research to support self evident points I won’t be including any of those things here. I will include How Tos and config files for those who are interested.

If there’s anything missing, let me know.

Productivity 2021

My second most popular post ever describes my Emacs Writing Setup. (My most popular post, if you’re interested, is this one.)

I wrote five novels and about thirty short stories using the method described in my Emacs Writing Setup, all the while experimenting with other methods. For example, I replicated some Scrivener features in Emacs and wrote about them here.

But over the past year all this has changed. So much so that I’m rewriting my Emacs Writing Setup from scratch.

So what’s changed? Briefly, I’ve started using Zettelkasten, org-roam and Doom Emacs for my writing flow. This has had a knock on effect for my productivity flow in general.

Over the next few months I’ll be going over my new set up. Let me know what you think.

You’re using folders and tags the wrong way round

According to Ian Small, CEO of Evernote, only 5% of Evernote users use tags. Evernote is not the only application that uses tags and folders, and I suspect the picture is similar in other applications. Most users rely on folders alone to categorize their work. I can understand this. Everyone has used paper folders in real life, the folders in applications replicate this experience.

However I think tagging is better, the reason being that although a note can only be in one folder, it can have more than one tag.

Here’s an example. Suppose you have personal notes and work notes. Some of those notes are just regular notes, some notes outline projects. You could tag your notes as follows:

  • Holiday (personal, project)
  • Shopping (personal)
  • User Manual (work, project)
  • Presentation (work)

Tagging like this gives you more flexibility. You can now filter for all of your projects, or filter for work projects only. By adding additional tags for things such as year 2021, 2022 you can then find, for example, all the personal projects you started in 2021.  Tagging gives your searches a granularity you don’t get by using folders.

Does that mean folders are no use? No. Folders are useful when something can only be on one state. A good example is :

  • Todo
  • In Progress
  • Done

You can set up those three folders and move notes between them. This is the opposite of the commonly recommended practice that you tag work with Todos.

Why are folders better? Because notes can only be in one folder at a time. It’s possible to accidentally tag a note as both Todo and Done. There’s also something quite satisfying about dragging a note from the In Progress to the Done folder…

What if you want to separate your work and personal to-dos? There are two ways. You can go to the Todo folder and filter by work or personal tags. Or it might be easier just to have two sets of folders

  • Work Todo
  • Work in Progress

And

  • Personal Todo
  • Personal in progress

Does it matter if you’re using folders and tags the wrong way round? Of course not. If you can find the right note at the right time, your system is fine. My suggestion is that using tags correctly adds flexibility.

Java Course 3: Random Numbers and Rounding

Random Numbers

Math.random() returns a random double between 0 and <1. Examples are 0.3332, 0.77777779 and 0.1113

To find a random number between 1 and 100, you’d need to do something like this:

double num = Math.random()*100;
int ran = (int)num+1;
System.out.println(ran);

Rounding and Formatting Decimals

double d = 3122.656774;
double roundUp = Math.round(d);
System.out.println(roundUp);

//Roundup to two decimal places
double roundUp2dp = Math.round(d*100)/100.0;
System.out.println(roundUp2dp);

//Formatting a number
//Note that the output is a string
DecimalFormat f = new DecimalFormat("#,###.00");
System.out.println(f.format(d));

Sample Formats

PatternNumberFormatted
###.###123.456123.456
###.#123.456123.5
###,###.##123456.789123,456.79
000.###9.95009.95
##0.###0.950.95

Exercise: Fahrenheit to Celsius

Here are the formulas to convert from Fahrenheit to Celsius and back again.

  • °F to °C: Deduct 32, then multiply by 5, then divide by 9
  • °C to °F: Multiply by 9, then divide by 5, then add 32
  1. Write a program to convert Fahrenheit to Celsius. Use the test data below to check your program.
  2. Now write a program to convert Celsius to Fahrenheit. Again, use the test data to check your program.

Test Data

CF
032
1254
100212
-327
-180
-23-10

Java Course 2: Types

Integers

// declare variables
int x;
int y;

// Instantiate Scanner
Scanner scan = new Scanner(System.in);

// Perform operation
System.out.println("Enter x?");
x = scan.nextInt();
System.out.println("Enter y?");
y = scan.nextInt();
System.out.println("x x y ="+ x*y);

Casting and Converting

Java is a statically, strongly typed language. You have to declare variable types before you use them (statically typed) and once declared, the variables cannot hold another type.

But sometimes you need to change the type. For example, in the code

int i =4;
System.out.println(i);

System.out.println(i) converts the int i into a String before printing out.

You can make an explicit conversion from int to String as follows

int i =4;
String s = Integer.toString(i);
System.out.println(s);

You can covert Double, Float etc to Strings similarly.

To convert the other way, e.g. from a String to an integer use the following

String s = "34"
int i = Integer.parseInt(s);

The fact that you can’t simply use i.toString() is an interesting one and part of a big debate about the way Java is put together. Briefly, Java doesn’t treat types like int and double as classes. That means you have to put them in a class wrapper when you want to perform some operations on them. Languages such as Scala treat all types as classes.

The following code will print out int c as a number and a char, depending on cast.

int c = 67;
System.out.println(c);
System.out.println((char)c);

Exercise: operations on int and double

  1. Write a program with two variables, length and width, that outputs the perimeter of a rectangle. Test it with length = 5 and width = 4.
  2. At the time of writing, the exchange rate for pounds to euros is 1 GBP = 1.19984 Euros. Write a program that will convert pounds to euros. Test it using the data GBP4.50
  3. Now write a program to convert euros to pounds. Test it using the data Euro 7.40
  4. Prompt the user to input a number. Output the square of that number.
  5. Prompt the user to input two numbers. Output the average of those two numbers.
  6. Prompt the user to input three numbers. Output the sum and the average of those three numbers.
  7. Assume pi = 3.1415. Prompt the user to input the radius of a circle. Output the circumference and the diameter of that circle

Good Practice

What’s the purpose of the following two code snippets? Which is better programming practice? Give some reasons why.

double x = 35.51*1.17;
System.out.println(x);

or

double pounds = 35.51;
double euroRate = 1.17;
double euros = pounds * euroRate;

System.out.println("£"+ pounds + " = " + euros + " euros");
System.out.println("at an rate of "+ euroRate + " euros to the pound");