Iterating over the lines of a file in Java

If you’re trying to write a standard command-line tool in Java you are going to experience pain.

In Python, if we want to do something with each line on input to your program, we can do something like:

import sys
for ln in sys.stdin:
    print(ln)  # (We have an extra newline but who's counting?)

In Java, after some fighting, the two closest alternatives I can find are:

import java.util.Scanner;
class IterateInputScanner {
    public static void main(String[] args) {
        for(String ln : (Iterable)(() -> new Scanner(System.in).useDelimiter("\n"))) {
            System.out.println(ln);
        }
    }
}

or, less fashionably, and even more horribly:

import java.io.BufferedReader;
import java.io.InputStreamReader;
class IterateInputReader {
    public static void main(String[] args) throws java.io.IOException {
        BufferedReader reader =
            new BufferedReader(new InputStreamReader(System.in));
        String ln;
        while((ln = reader.readLine()) != null) {
            System.out.println(ln);
        }
    }
}

Note that if you are reading from a stream other than stdin you will probably want to wrap this in a try-with-resources to close the stream when you’ve finished.

Take your pick, and I hope it saves you some fighting.

Raspberry Pi Jam “Chaos Car!”

Raspberry Pi 1
+ battery pack
+ Bluetooth USB dongle
+ i-racer bluetooth car
+ Raspberry Pi camera
+ some Python code
+ loads of sellotape
=

Chaos car!

Here’s the code:

#!/usr/bin/env python2

import os
import random
import bluetooth
import sys
import time

car_name = "DaguCar"

def find_car_mac( car_name ):
    ret = None

    print "Scanning for a device called %s..." % car_name

    devices = bluetooth.discover_devices()

    for addr in devices:
        dev_name = bluetooth.lookup_name( addr )
        if dev_name == car_name:
            print "Car found!  (MAC=%s)" % addr
            time.sleep( 1 )
            return addr
        else:
            print "Skipping device named '%s'." % dev_name

    sys.stderr.write( "Couldn't find a device called %s!\n" % car_name )
    sys.exit( 1 )


#car_mac = find_car_mac( car_name )

print "Using hard-coded MAC address"
car_mac = "20:13:04:23:05:71"

print "Connecting to the car at %s..." % car_mac

sock = bluetooth.BluetoothSocket( bluetooth.RFCOMM )
sock.connect( ( car_mac, 1 ) )

class Car:
    def turn_right(self):
        print("looking right")
        sock.send( '\x6A' )
    def turn_left(self):
        print("looking left")
        sock.send( '\x5A' )
    def roll_forward(self):
        print("watch out in front coming forward")
        sock.send( '\x1A' )
    def roll_backward(self):
        print("beep beep going backward")
        sock.send( '\x2A' )
    def wait(self):
        print("waiting")
        sock.send( '\x00' )

car = Car()

instruction = ["turn right", "turn left", "roll forward", "roll backward", "wait"]

while True:
    ci = random.choice(instruction)
    if ci == "turn right":
        car.turn_right()
    elif ci == "turn left":
        car.turn_left()
    elif ci == "roll forward":
        car.roll_forward()
    elif ci == "roll backward":
        car.roll_backward()
    elif ci == "wait":
        car.wait()
    time.sleep(0.5)

Improving the code to avoid bumping into walls is left as an exercise for the reader.

Resources for year 6 teachers on coding and programming

I have been introducing some year 6 (UK) teachers to coding by showing them how to lay out a simple web page by writing HTML. I promised I would find some links to resources for them, so here it is:

HTML and JavaScript

My examples of how to write HTML are at github.com/andybalaam/html-examples

There are several web sites that allow you to experiment with writing HTML and JavaScript and seeing the results immediately:

I also made some videos about how to make a snowflake animation in both JavaScript and Scratch here: Snowflake Christmas card.

Raspberry Pi

The Raspberry Pi is a cheap education-focussed computer that looks like a piece of circuit board the size of a credit card.

Their educational resources are at: raspberrypi.org/resources.

There are lots of great videos about how to do different things with the Raspberry Pi, including the ones by The Raspberry Pi Guy.

There are also my (boring, but comprehensive) videos teaching you to write a simple game in Python, from a starting point of no programming experience at all: My First Raspberry Pi Game.

Graphical programming

There are several tools and sites for learning programming by dragging and dropping blocks instead of typing code:

  • Scratch – creative, unguided, a bit old-fashined looking but tried-and-trusted
  • code.org – fun, attractive guided tasks featuring Disney characters, Minecraft etc.
  • blockly – guided tasks with good progression
  • codeforlife.education – I’ve not used this, but it looks like it could have potential

Other languages

Writing a unit test in Elm

Series: Snake in Elm, Elm makes me happy, Elm Basics, Elm Unit Test

I’ve been having fun with Elm programming recently. Elm is a replacement for JavaScript that is pure functional and highly practical.

Here’s how to go from nothing installed at all to writing a unit test that passes, in just over 10 minutes.

The source code is here: github.com/andybalaam/elm-unit-test-example

How to write a programming language – Part 3, The Evaluator

Series: Lexer, Parser, Evaluator.

Finally, we get onto the actual magic of the little language I wrote (Cell) – the evaluator, which takes in syntax trees and finds their real value, in the context of the “environment”: the symbols that are defined around it.

Slides: How to write a programming language – Part 3, The Evaluator

If you want to, you can Support me on Patreon.