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.

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.

How to write a programming language – Part 2, The Parser

Series: Lexer, Parser, Evaluator

My little programming language, Cell (Cell Elementary Learning Language) is designed to be simple. I want to use it to explain how to write a programming language. The parser is only 81 lines long, so hopefully it’s not too hard to understand.

Here’s the explanation of the parser, which is the second part of a compiler or interpreter.

Slides: How to write a programming language – Part 2, The Parser

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

How to write a programming language – Part 1, The Lexer

Series: Lexer, Parser, Evaluator

I wrote a little programming language, Cell which is supposed to be simple enough to help explain how a programming language works.

Here’s the explanation of the lexer, which is the first part of a compiler or interpreter.

Slides: How to write a programming language – Part 1, The Lexer

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