Skip navigation

Bits, Types, Characters and Type Casting in Java. Learning objectives and exercises from the University of London BSc in Creative Computing.
 
LEARNING OBJECTIVES
 
1. Understand that different variables of different types have different sizes.
 
A variable consists of some bytes (8 bits) of RAM. Different variable types have a different amount of memory required. A boolean variable only requires one bit as it can only be true or false. For storing characters, Java allocates two bytes which provides space for 216 different characters to be stored (which is 65,536 characters). For storing int variables, Java allocates 4 bytes, which is 232 integers.
 
2. Explain type casting.
 
You can force Java to treat an expression as belonging to a particular type by including the type in brackets before the expression. So the expression System.out.println((char)37); will print out the char ‘%’ rather than the int 37.
 
3. Explain the relationship between characters and Unicode.
 
Unicode is a method of allocating a particular integer value to a character so that the computer is able to display different types of natural language and alphabet. Each character and symbol in a specific alphabet is allocated a number within a specific Unicode encoding. There are many Unicode encodings. Some examples are UTF-8, UTF-16, ASCII, Mac OS Roman etc. Each encoding has a different mapping of characters to integers. Follow the Unicode link to Wikipedia for more information.
 
4. Explain why the read method returns an int.
 
As Java allocates all 216 possible spaces in char memory to characters there is no room for any ‘special characters’ like a ‘line return’ or ‘end of file’. These special characters have to therefore be stored in a variable type that has more memory space. The read() method uses the return type int which has 232 possible integers that it can store. Therefore we can use the read() method to input characters other than just char characters. Because they are stored as Unicode integers, we must type cast the output of read() back to char for proper display.
 
EXERCISES
 
Q: Research each type in Java and find out how big it is.
 
The size of primitive data types (those that are automatically part of the Java program language) can be found here. Below are the sizes of the key data types:
 
int: 32 bits
long: 64 bits (twos-complement)
float: 32 bit (floating point)
double: 64 bit (floating point)
boolean: 1 bit
char: 16 bits
short: 16 bits (twos-complement)
byte: 8 bits (two-complement)
 
String is not strictly a primitive data type, rather it is an object from the class java.lang.String.
 
Q: Write a program to check whether or not an int can be cast as a boolean.
 
An int cannot be cast as a boolean. The compiler complains if you try to do this.
 
Q: Write a program to check whether or not a boolean can be cast as an int.
 
No, this does not work either – a boolean cannot be cast as an int.
 
Q: Write a program to check whether or not a float can be cast as an int.
 
CODE: FloatToInt

class FloatToInt
{
    
public static void main(String[] args)
    {
        
float in = 1.0000f//the'f' defines the value as a float
        int out = (int)in;
        
System.out.println(out);
    }
}

 
Yes, it is possible to cast a float as an int. You will necessarily lose data and accuracy by doing this.
 
Q: Write a program to check whether or not a double can be cast as a float.
 
CODE: DoubleToFloat.java

class DoubleToFloat
{
    
public static void main(String[] args)
    {
        
double in = 1.0;
        
float out = (float)in;
        
System.out.println(out);
    }
}

 
Yes, a double can be cast to a float variable.
 
Q: Write a program to check whether or not an int can be cast as a float.
 
CODE: IntToFloat.java

class DoubleToFloat
{
    
public static void main(String[] args)
    {
        
double in = 1.0;
        
float out = (float)in;
        
System.out.println(out);
    }
}

 
Yes, it is possible to cast an int as a float.
 
Q: Write a program to check whether or not a float can be cast as a char.
 
CODE: FloatToChar.java

class FloatToChar
{
    
public static void main(String[] args)
    {
        
float in = 100.0f//f designates the value is a float
        char out = (char)in;
        
System.out.println(out);
    }
}

 
Yes, it is possible to cast a float as a char.
 
Q: Write a program to check whether or not an int can be cast as a short.
 

class IntToShort
{
    
public static void main(String[] args)
    {
        
int in = 1000;
        
short out = (short)in;
        
System.out.println(out);
    }
}

 
Yes, an int can be cast as a short but for large integers (above 32,768 and below -32,768) a loss of data and accuracy will occur.
 

More about variables in Java. Learning objectives and exercises from the University of London BSc in Creative Computing.
 
LEARNING OBJECTIVES
 
1. Explain the concept of local variables and the scope of variables.
 
A local variable is a variable that is declared within a method or some other programming structure (like a for loop for example). Variables declared outside a method or a for loop are referred to as global variables.
 
2. Explain the concept of simple and reference variables.
 
Simple variables (types like int, char etc) actually store the value assigned to them in their allocated space in memory. On the other hand reference variables store the address in memory where the actual values are stored. Reference variables like String and array variables will store their contents somewhere in memory and will store that location as a value in the variable’s memory allocation.
 
3. Explain how the values of these variables are passed as parameters to methods.
 
When we pass variables as parameters into a method, we are essentially creating local copies of those variables for the use of the method only. Even if the variables have the same name, they can hold different values. Unless a global variable is assigned the value of a local variable, the value of the global variable will remain unchanged, irrespective of the functions applied to the local variable within the method.
 
EXERCISES
 
Q: Consider and explain the following code example.
 
CODE: arrayParams.java

class arrayParams
{
    
public static void main(String [] args)
    {
        
int[] a = new int[1];
        
a[0] = 1;
        
p(a);
        
System.out.println(a[0]);   //This prints 5
    }
    
static void p(int[] m)
    {
        
m[0]=5;
    }
}

 
Got this completely wrong when I first tried to answer this question. Intuitively, you would imagine that because the array int[] m is a local variable, the method p() should have no effect on the global array variable a[0]. However, because int[] is a reference variable, and the address of the array a is passed into the method as p(a), the assignment of the value 5 by the local array variable m[0]means that the value of a[0] is also changed because m[0] is referencing the same address in memory as a[0].
 
Q: Consider and explain the following code example.
 
CODE: arrayParams2.java

class arrayParams2
{
    
public static void main(String [] args)
    {
        
int[] a = new int[1];
        
a[0] = 5;
        
p(a);
        
System.out.println(a[0]);   //This prints 5
    }
    
static void p(int[] m)
    {
        
mnew int[3];
        
m[0]=7;
    }
}

 
Here, within the p() method, a new local array, m, is declared which will point to a new location in memory (not the location of the array a). Therefore the assignment m[0]=7; has no effect on the location of a[0]. It therefore maintains the value 5 assigned in the main body of the program.
 
Q: Consider and explain the following code.
 
CODE: StringParams.java
 

class StringParams
{
    
public static void main(String [] args)
    {
        
String n = "Hello";
        
p(n);
        
System.out.println(n);  //This prints hello
    }
    
static void p(String m)
    {
        
m"Goodbye";
    }
}

 
Again, intuitively this feels like the example in the first exercise – but it would appear that it is not. The difference here is that the assignment of m="Goodbye"; actually has the effect of creating a new string and therefore a new location in memory for the contents of variable m, meaning that the content of the memory location referenced by n remains unchanged. Therefore the program prints out ‘Hello’.
 
Q: Consider and explain the following program.
 
CODE: TestArray.java

class TestArray
{
    
static void change(int[] a)
    {
        
a[0]=17;
    }
    
public static void main (String[] args)
    {
        
int[] znew int[2];
        
z[0]=1;
        
z[1]=2;
        
change(z);
        
Arrays.printarray(z,2);
    }
}

 
This program prints out ’17 2′ for the reasons outlined in the first exercise example.
 
Q: Consider and explain the following program.
 
CODE: TestInt.java

class TestInt
{
    
static void change(int a)
    {
        
a=17;
    }
    
public static void main (String[] args)
    {
        
int z=5;
        
change(z);
        
System.out.println(z);
    }
}

 
This program prints out ’5′. This is because int is a simple variable – the global variable int z is unchanged by an assigment to a local simple variable int a. They are stored in different memory locations and therefore do not affect one another.

Packaging programs in Java. Learning objectives and exercises from the University of London BSc in Creative Computing.
 
LEARNING OBJECTIVES
 
1. Explain the purpose of the CLASSPATH system variable.
 
The CLASSPATH system variable tells Java (via your computer’s operating system) where to look for the programs (or .class files) that are referenced in a command line execution. If you want to execute the command java syr 14 as we did in the last post, your system needs to know where to look on your computer for the syr.class file. CLASSPATH provides the OS the information it needs to be able to do this by specifying the top level directory under which all your .class files are stored.
 
You set the CLASSPATH on a UNIX system (which is the underlying operating system used by the Mac that I develop on) by the following command line statement:
 
CLASSPATH=$HOME/[name of the top level directory where your java programs are stored]:$CLASSPATH
export CLASSPATH

 
2. Explain the purpose of the package statement.
 
The package statement needs to be inserted at the beginning of a Java program. It tells Java that the program (.class file) belongs to a directory structure that sits underneath the CLASSPATH top-level directory and also allows us to call the methods within it using dot.notation. The best way to explain it is by way of an example. If a Java .class file is situated at [CLASSPATH]/Dir1/Dir2 and contains a package statement at the beginning of the program thus, package Dir1.Dir2;, then the methods within it can be called from another program that sits underneath CLASSPATH by using dot.notation. So, if the original .class file contains a method called example(), then the same method can be called from another program within the CLASSPATH directory structure by the following statement Dir1.Dir2.example();. Phew!!
 
Gets more complicated – if you want to call a method from outside the package (and thereby the directory) in which it is declared, you must declare the method as public.
 
Another anomaly to be aware of – if we are calling a program from a package by another program within the same sub-directory, the calling program must be declared as part of the same package.
 
3. Explain the purpose of the import statement.
 
Using the import statement saves us time when coding by allowing us to easily use methods which are parts of different directory and therefore package structures. We can import all classes and methods contained within a particular package using the import statement. So, in the example previously, we could call the method example() without using dot.notation if we included the statement import Dir1.Dir2.*; at the beginning of our program (as long as our program existed within the CLASSPATH directory structure).
 
If you are calling a program in a package from within the same package, you don’t need to use an import statement.
 
2. Explain how to run a Java program that is part of a package, from the command line.
 
Continuing our example above, if the .class file that contains the method example() which has been defined in the package Dir1.Dir2 is called Hello.class then we can (and in fact MUST) run that file from the command line by typing java Dir1.Dir2.Hello. As soon as a class has been defined as part of a package, you will generate a compiler error if you try to run the class without its package dot.notation signature.
 
EXERCISES
 
Q: Consider the following Java program:

import java.util.Scanner;
class EchoNew
{
    
public static void main(String[] args
    {
        
Scanner in =new Scanner(System.in);
        
String s =in.nextLine();
        
System.out.println(s);
    }
}

 
How would it have to be written if there was no import statement in Java?

 
If we were to remove the import statement we would need to include the full package structure within our calls to Scanner() as below.
 
CODE: EchoNew.java

class EchoNew
{
    
public static void main(String[] args
    {
        
java.util.Scanner in =new java.util.Scanner(System.in);
        
String s =in.nextLine();
        
System.out.println(s);
    }
}

 
Q: Write a complete java application by calling methods from the class ArraysNew detailed below, which asks the user how many number they are going to enter, reads in the numbers and prints their average.

package Lecture15;
import java.util.Scanner;
public class ArraysNew
{
    
    
public static int sum(int[] a)
    {
        
int sum=0;
        
for (int i=0i<a.lengthi++) sum=sum+a[i];
        
return sum;
    }
    
public static int largest(int[] a)
    {
        
int largest=a[0];
        
for (int i=1i<a.lengthi++) if (a[i]>largestlargest=a[i];
        
return largest;
    }
    
public static int smallest(int[] a)
    {
        
int smallest=a[0];
        
for (int i=1i<a.lengthi++) if (a[i]<smallestsmallest=a[i];
        
return smallest;        
    }
    
public static double average(int[] a)
    {
        
return (sum(a)*1.0)/a.length;
    }
    
public static void print(int a[])
    {
        
for (int i=0i<a.lengthi++) System.out.println(a[i]);
    }
    
public static int[] readintarray()
    {
        
Scanner in = new Scanner(System.in);
        
System.out.println("How many numbers are you going to enter? ");
        
int n = in.nextInt();
        
System.out.println("Enter " + n + " numbers ");
        
int[] a;    //declares a to be an array of ints
        a =new int[n];  //gives enough space to hold n ints
        for (int i=0i<ni++)     //read them into an array
        {
            
a[i]=in.nextInt();
        }
        
return a;
    }
}


Answer below.
 
CODE: TestPackage.java

package Lecture15;
class TestPackage
{
    
public static void main(String[] args)
    {
        
System.out.println("The average of the array is " 
        + 
ArraysNew.average(ArraysNew.readintarray()));
    }
}

 
Q: Add your own method to the class ArraysNew which multiplies the elements of an array together. Write a complete application that uses this method to compute factorial.
 
So, writing a method to multiply the elements of an array together is not a big deal. However, to work out the factorial of an array makes no sense. The function factorial only makes sense when we are talking about the factorial of an integer not an array of integers. The approach I have therefore taken is to work out the largest element of the array and work out the factorial of that element. The amended ArraysNew code plus the complete application is shown below.
 
CODE: ArraysNew.java

package Lecture15;
import java.util.Scanner;
public class ArraysNew
{
    
    
public static int sum(int[] a)
    {
        
int sum=0;
        
for (int i=0i<a.lengthi++) sum=sum+a[i];
        
return sum;
    }
    
public static int largest(int[] a)
    {
        
int largest=a[0];
        
for (int i=1i<a.lengthi++) if (a[i]>largestlargest=a[i];
        
return largest;
    }
    
public static int smallest(int[] a)
    {
        
int smallest=a[0];
        
for (int i=1i<a.lengthi++) if (a[i]<smallestsmallest=a[i];
        
return smallest;        
    }
    
public static double average(int[] a)
    {
        
return (sum(a)*1.0)/a.length;
    }
    
public static void print(int a[])
    {
        
for (int i=0i<a.lengthi++) System.out.println(a[i]);
    }
    
public static int[] readintarray()
    {
        
Scanner in = new Scanner(System.in);
        
System.out.println("How many numbers are you going to enter? ");
        
int n = in.nextInt();
        
System.out.println("Enter " + n + " numbers ");
        
int[] a;    //declares a to be an array of ints
        a =new int[n];  //gives enough space to hold n ints
        for (int i=0i<ni++)     //read them into an array
        {
            
a[i]=in.nextInt();
        }
        
return a;
    }
    
    
//this is the new method that I've added in below
    
    
public static int mult(int[] a//multiples array members together
    {
        
int tot=1;
        
for (int i=0i<a.lengthi++) tot=tot*a[i];
        
return tot;
    }
}

 
CODE: FactArray.java

package Lecture15;
class FactArray
{
    
public static void main(String[] args)
    {
        
int largest = ArraysNew.largest(ArraysNew.readintarray()); 
        
System.out.println("The largest integer in the array is " 
        + 
largest);
        
//fill up an array for the ArraysNew.mult() method to use
        int[] FactArray = new int[largest];
        
for (int i=largest-1i>=0i--)
        {
            
FactArray[i] = largest;
            
largest--;
        }
        
System.out.println("The factorial of the largest integer in the"
        + 
" array is " + ArraysNew.mult(FactArray));
    }
}

LEARNING OBJECTIVES
 
1. Explain what a recursive method is.
 
A recursive method is a method that calls itself and is a very powerful technique in computer science. More details on recursion can be found in the post about Structure in the Image, Sound and Motion category of this blog.
 
2. Explain how to define and use recursive methods.
 
The exercises below demonstrate how to use recursion in Java.
 
EXERCISES
 
Q: Write a program such that java fibonacci n prints out the nth Fibonacci number. The Fibonacci sequence goes 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,….
 
Firstly we need to define what the Fibonacci sequence is. By definition the first two numbers of the sequence are 0 and 1 (so we will ignore those for the sake of this calculation). All other members of the sequence are calculated by the sum of the previous two numbers in the sequence. We can then create a recursive method that calls itself as below.
 
CODE: fibonacci.java

public class fibonacci
{
    
static int fib(int n)
    {
        
if (n==0 || n==1return 1;
        
else return fib(n-1) + fib(n-2);
    }
    
public static void main(String[] args)
    {
        
System.out.println("Number " + args[0] + " in the Fibonacci"
        + 
" sequence is " + fib(Integer.parseInt(args[0])));    
    }       
}

 
Q: Multiplication of non-negative integers can be defined recursively in terms of addition. Write a class which has a method mult which implements such a function.
 
CODE: multiplication.java

public class multiplication
{
    
static int mult(int nint m)
    {
        
if (m==0return 0;
        
else return n+mult(n,m-1);
    }
    
public static void main(String[] args)
    {
        
System.out.println(args[0] + " multiplied by " + args[1] +
        
" = " + mult(Integer.parseInt(args[0]), 
        
Integer.parseInt(args[1])));    
    }       
}

 
Q: Exponentiation of non-negative integers can be defined recursively in terms of multiplication. Write a class which has a method power() which implements such a function.
 
CODE: exponentiation.java

public class exponentiation
{
    
static int power(int nint m)
    {
        
if (m==0return 1;
        
else return mult(n,power(n,m-1));
        
//note, could have written
        //else return n*power(n,m-1).
        //used the mult() method because
        //I had already written it
    }
    
static int mult(int nint m)
    {
        
if (m==0return 0;
        
else return n+mult(n,m-1);
    }
    
public static void main(String[] args)
    {
        
System.out.println(args[0] + " to the power of " + args[1] +
        
" = " + power(Integer.parseInt(args[0]), 
        
Integer.parseInt(args[1])));    
    }       
}

 
Q: Without using vectors or arrays write a program which reads in characters from the keyboard and prints them out in the opposite order to which they were typed in. The program should end when the user presses the enter key.
 
Without wanting to be disparaging to the UoL, the solution provided in the course notes makes use of code that is not taught for at least another 5 chapters, so at this point, I won’t be providing an answer to this problem (but I’ll come back to it!).
 
Q: The Syracuse Sequence starting with 14 goes like this: 14, 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1
 
The rule is as follows: if n is even then the next number in the sequence is n/2 and if n is odd, the next number is 3n + 1. The sequence stops at 1. Using recursion, write a program not containing the word ‘while’, such that for all positive integers, n, java syr n prints out the Syracuse sequence starting with n.

 
Struggled with this one for a while, not because of the logic (although that did test me for a while) but because I was used to writing a non-void method (that is, one that returns a value). Was able to do it, but when the sequence got to 1, needed to return something so ended up having two ’1′s at the end of each sequence (which is wrong!). Using a void method (inspired by the course note answer) was able to adjust to a much simpler program as below.
 
CODE: syr.java

public class syr
{
    
static void syrac(int n)
    {
        
System.out.println(n);
        
if (n==1return;
        
else if ((n%2)==0syrac(n/2);
            
else syrac((3*n)+1);
    }

    public static void main(String[] args)
    {
        
System.out.println("Syracuse sequence starting with " + args[0] +" is");
        
syrac(Integer.parseInt(args[0]));
    }       
}

LEARNING OBJECTIVES
 
1. Explain the purpose of command-line arguments.
 
Command line arguments are used to pass parameters into the main() program method at the beginning of the program execution.
 
2. Explain how to use command-line arguments.
 
When we define the main() method we write:
 
public static void main(String[] args)
 
args is a parameter in the main() method and is an array of type String. When we run a program from the command-line we type something like:
 
java NewArray
 
However we can include any other parameters after the name of the program. Each of these parameters is passed into the args string array and can be used within the program. The first parameter is args[0], the second args[1] etc. We can work out the number of elements in the args array by using args.length as we saw in the previous post’s exercises. It’s important to remember that the elements in the args array are stored as strings, even if they are input as integers. To convert from a string to an integer we use the method Integer.parseInt(). Also, we could call the parameter args anything we like, we don’t have to use args although it is convention to do so.
 
EXERCISES
 
Q: Write a program which prints out one more than its command-line argument.
 
CODE: AddOne.java

class AddOne
{
    
public static void main(String[] args)
    {
        
System.out.println("One plus command line argument = "
        + (
Integer.parseInt(args[0])+1));
    }
}

 
Q: Write a program which adds its two command line arguments.
 
CODE: SumTwo.java

class SumTwo
{
    
public static void main(String[] args)
    {
        
System.out.println("Sum of command line arguments = "
        + (
Integer.parseInt(args[0])+Integer.parseInt(args[1])));
    }
}

 
Q: Write a program that allows you to enter as many words as you like as command-line arguments and the program prints them out in reverse order.
 
CODE: ReverseWords

class ReverseWords
{
    
public static void main(String[] args)
    {
        
//work out the length of args[]
        int len=args.length;
        
//cycle backwards through the array
        for (int i = len-1i>=0i--)
        {
            
System.out.println(args[i]);
        }
    }
}

 
Q: Write a program that prints out the average of all its command line arguments
 
CODE: averageCommandLine.java

class averageCommandLine
{
    
public static void main(String[] args)
    {
        
//work out the length of args[]
        int len=args.length;
        
int sum=0;
        
//sum the array
        for (int i=0i<leni++)
        {
            
sum = sum + Integer.parseInt(args[i]);
        }
        
double average=(sum*1.0)/len;
        
System.out.println(average);
    }
}

 
Q: Write a program that prints out the longest of all its command line arguments.
 
This program works out the longest string input as a command line argument. It two or more strings are the same length it will output the last string it encountered that has the longest length. I wrote a program in the One Dimensional Arrays post which contains the full code for checking when two strings are the same length which can be found here.
 
CODE: longestCommandLine.java

class longestCommandLine
{
    
public static void main(String[] args)
    {
        
//work out the length of args[]
        int len=args.length;    //.length can be used for arrays
        int longest=0;
        
int counter=0;
        
//cycle through the array
        for (int i=0i<leni++)
        {
            
//.length() should be used for strings
            if(args[i].length()>longest)    
            {
                
longest=args[i].length();
                
counter=i//keeps track of which word is longest
                System.out.println("longest =" + longest);
            }
        }
        
System.out.println(args[counter]);
    }
}

 
Q: Write a program that prints out all its command-line arguments characters backwards. So java back Fred Bloggs should output derF sggolB.
 
CODE: Back.java

class Back
{
    
public static void main(String[] args)
    {
        
//work out the length of args[]
        int len=args.length;
        
//cycle forwards through the array string
        for (int i=0i<leni++)
        {
            
//how long is the word in characters?
            int wordLen = args[i].length();
            
//cycle backwards through the word a char at a time
            for (int j=wordLen-1j>=0j--)
            {
                
System.out.print(args[i].charAt(j));
            }
        
System.out.print(" ");
        }
        
    }
}

LEARNING OBJECTIVES
 
1. Understand why methods are useful.
 
Methods are sub-routines or separate pieces of code that can be used repeatedly. We can write the code once and use it over and over again.
 
We don’t need to understand how a method works, just that it does – and what it does! Sometimes methods return a value and sometimes they just do things and don’t return a value (and sometimes they do both). We will define these key differences more precisely later in this post.
 
Methods are useful because they are more readable and easier to understand for a programmer than straight code. They can help us break down large problems into smaller solvable packets and, of course, they are reusable.
 
2. Learn how to define void static methods.
 
In order to define a static method we need both a method heading and method body.
 
The method heading, the first line of the method, tells us whether it is static or not as well as the signature of the method. The signature is the list of parameters contained within the () that the method can accept.
 
A method is void if it does not return a value. A void method just does something, but doesn’t return the output of a calculation or process.
 
After the first line, the remainder of the code is called the body of the method.
 
3. Learn how to use parameters.
 
If we want methods to perform different tasks each time they are called, we need to use parameters. The parameters appear within the () of the method and are separated by commas.
 
The parameters within the method are passed into and used within the routine. In this way, we can change the parameters in the heading and have the body of the routine perform different tasks.
 
The names of the parameters should indicate their use as much as possible to help other programmers reading the code to understand what it does and how it works.
 
4. Learn how to define non-void static methods.
 
A non-void static method is one that does return a value (as opposed to a void method that does not). Within a non-void method we need to include a return statement.
 
A non-void method can be used as an expression, which is defined as anything that can appear after the = sign in an assignment statement. A void method cannot.
 
5. Understand return types.
 
Return types are like variable types, they specify to the compiler in what format the data is going to be input into and returned from the method. A non-void method example int (int) will take an integer as a parameter into the method and return an integer from the method.
 
EXERCISES
 
Q: Modify the code below to use methods.
 
CODE: timesTable.java

//multiple times tables
import java.util.Scanner;
class timesTable
{
    
public static void main(String[] args)
    {
        
//input
        Scanner in = new Scanner(System.in);
        
System.out.println("How many numbers for each table? > ");
        
int num = in.nextInt();
        
System.out.println("Up to which times table? > ");
        
int times = in.nextInt();
        
System.out.println();   
        
//calculation and printing
        for (int i=1i<=numi++)
        {
            
for (int j=1j<=timesj++)
                {
                    
System.out.println(j + " times " + i + 
                    
" = " + (j*i));
                }
            
System.out.println();   
        }
    }
}

 
The following is a very quick solution to this problem – in effect all I have done is move the calculation element of the previous program into a static void method called calc(). Given more time, this program could be altered to not use loops but that wasn’t what was requested in the exercise so I’m going to leave this code as is for the time being.
 
CODE: timesTableMethod

//multiple times tables
import java.util.Scanner;
class timesTableMethod
{
    
public static void calc(int aint b)
    {
        
for (int i=1i<=ai++)
        {
            
for (int j=1j<=bj++)
            {
                
System.out.println(j + "times" + i +
                
" = " + (j*i));
            }
            
System.out.println();
        }
    }
    
public static void main(String[] args)
    {
        
//input
        Scanner in = new Scanner(System.in);
        
System.out.println("How many numbers for each table? > ");
        
int num = in.nextInt();
        
System.out.println("Up to which times table? > ");
        
int times = in.nextInt();
        
System.out.println();   
        
//calculation and printing
        calc(numtimes);
    }
}

 
Q: Write a program which asks the user to enter a number n, say, and it outputs 1 + … + n.
 
CODE: seriesSum.java

import java.util.Scanner;
class seriesSum
{
    
public static int SS (int end)
    {
        
int sum = 0;
        
for (int i=1i<=endi++)
        {
            
sum = sum + i;
        }
        
return sum;
    }
    
public static void main(String[] args)
    {
        
//input
        Scanner in = new Scanner(System.in);
        
System.out.print("Input n > ");
        
int n = in.nextInt();
        
System.out.println();
        
//calculation
        System.out.println("The sum of 1 + ... + n is " + SS(n));
        
System.out.println();
    }
}

 
Q: Write non void methods to work out:
 
1. The sum of all elements in an array
2. The largest of all elements in an array
3. The smallest of all the elements in an array
4. The average of all the elements in an array
 
Put all the methods in a class called ArrayUseful.

 
The following code is ©UoL. I developed my own code but it was not as neat as the code below, so for the sake of revision notes I’ll use the UoL example answers here.
 
CODE: ArrayUseful.java ©UoL

class ArrayUseful
{
    
static int sum(int[] a)
    {
        
int sum=0;
        
for (int i=0i<a.lengthi++)  //it would appear
                                        //that you can use
                                        //a.length in Java
                                        //to work out the
                                        //length of an
                                        //array!
        {
            
sum = sum + a[i];
        }
        
return sum;
    }
    
static int largest(int[] a)
    {
        
int largest=a[0];
        
for (int i=1i<a.lengthi++) 
        {
            
if (a[i]>largest)
            {
                
largest=a[i];
            }
        }
        
return largest;
    }
    
static int smallest(int[] a)
    {
        
int smallest=a[0];
        
for (int i=1i<a.lengthi++)
        {
            
if (a[i]<smallest)
            {
                
smallest = a[i];
            }
        }
        
return smallest;
    }
    
static double average(int[] a)
    {
        
return (sum(a)*1.0)/a.length;
    }
}

 
Notice in the last method average() that it is actually calling one of the previously defined methods sum() into it.
 
Q: Write a program that uses the methods we have just defined by reading some numbers into an array and prints out the largest, the smallest, the sum and the average of the numbers.
 
CODE: ArrayNew.java

import java.util.Scanner;
class ArrayNew
{
    
public static void main(String[] args)
    {
        
int size = 0;
        
//input some numbers
        Scanner in = new Scanner(System.in);
        
System.out.print("How many numbers will you enter? ");
        
size = in.nextInt();
        
System.out.println();
        
int [] array;
        
array = new int[size];
        
System.out.println("Enter " + size + " numbers> ");
        
for (int i=0i<sizei++)
        {
            
array[i] = in.nextInt();
        }
    
    
//Note below that we use dot.notation to call in the methods
    //from the class ArrayUseful which is stored in the same directory
    //as this program
    
    
System.out.println("The sum of these numbers is " + 
    
ArrayUseful.sum(array));
    
    
System.out.println("The largest of these numbers is " +
    
ArrayUseful.largest(array));
    
    
System.out.println("The smallest of these numbers is " +
    
ArrayUseful.smallest(array));
    
    
System.out.println("The average of these numbers is " +
    
ArrayUseful.average(array));
        
    }
}

LEARNING OBJECTIVES
 
1. Learn how to solve problems using loops within loops.
 
It is possible to place a ‘loop within a loop’ in Java. We create a loop using a for statement where the guard condition defines the number of times the loop should be executed.
 
By enclosing a for statement within another for statement we create two loops, the inner and outer loop. First the outer loop executes until it hits the the inner loop statement. The inner loop then executes until it hits its guard condition, at which point it returns control to the outer loop code which then cycles through the remaining statements and returns to the beginning. This process continues until the outer loop reaches its guard condition at which point the program moves on.
 
Examples of this technique can be seen in the Exercises section below.
 
EXERCISES
 
Q: Write a program to output a triangle of stars with the right angle at the bottom right of the screen.
 
CODE: StarsTriRB.java

// right-bottom right angle triangle

import java.util.Scanner;
class StarsTriRB
{
    
public static void main(String[] args)
    {
        
Scanner innew Scanner(System.in);
        
System.out.print("Enter Width>");
        
int x=in.nextInt();
        
int k;
        
for (int j=0j<xj++)
        {       
            
k=x-j;      //k allows the program print decreasing
                        //amounts as the loop count increases
            
            
// print the spaces before the stars
            // the (k-1) leaves room in the spaces for the
            // stars
            for (int n=0n<(k-1); n++) System.out.print(" ");
            
// print the stars
            // the (j+1) makes sure that there is no row
            // with no stars in it
            for (int i=0i<(j+1); i++) System.out.print("*");
            
System.out.println();
        }
    }
}

 
Q: Write a program to output a hollow rectangle of stars.
 
CODE: HollowStars.java

// hollow rectangle of stars
import java.util.Scanner;
class HollowStars
{
    
public static void main(String[] args)
    {
        
Scanner innew Scanner(System.in);
        
System.out.print("Enter Width>");
        
int x=in.nextInt();
        
for (int j=0j<xj++)
        {       
            
if (j==0 || j==(x-1))   //top or bottom of rectangle
            {
                
for (int i=0i<xi++) System.out.print("*");
                
System.out.println();
            }
            
if (j>0 && j<(x-1))     //middle of rectangle
            {
                
System.out.print("*");
                
// (x-2) to leave enough room for stars
                for (int i=0i<(x-2); i++)
                    {
                        
System.out.print(" ");
                    }
                
System.out.print("*");
                
System.out.println();
            }
        }
    }
}

 
Q: Write a program to print out all the times tables. The user should enter how many tables and also how many to go up to for each table.
 
CODE: timesTable.java

//multiple times tables
import java.util.Scanner;
class timesTable
{
    
public static void main(String[] args)
    {
        
//input
        Scanner in = new Scanner(System.in);
        
System.out.println("How many numbers for each table? > ");
        
int num = in.nextInt();
        
System.out.println("Up to which times table? > ");
        
int times = in.nextInt();
        
System.out.println();   
        
//calculation and printing
        for (int i=1i<=numi++)
        {
            
for (int j=1j<=timesj++)
                {
                    
System.out.println(j + " times " + i + 
                    
" = " + (j*i));
                }
            
System.out.println();   
        }
    }
}   

 
Q: Imagine Java did not have a multiplication function. Write a program that asks the user to enter two whole numbers and then outputs their product. Your program should use a loop and no multiplication sign anywhere!

CODE: multiAdd.java

//multiplication by addition
import java.util.Scanner;
class multiAdd
{
    
public static void main(String[] args)
    {
        
System.out.println();
        
System.out.println("Multiplying two number by addition");
        
System.out.println();
        
//input
        Scanner in = new Scanner(System.in);
        
System.out.print("Enter the first integer> ");
        
int numOne = in.nextInt();
        
System.out.print("Enter the second integer> ");
        
int numTwo = in.nextInt();
        
System.out.println();   
        
//calculation and printing
        int sum=0;
        
for (int i=0i<numOnei++)
            {
                
sum=sum+numTwo;
            }
            
            
System.out.println("Answer is " + sum);
            
System.out.println();
    }
}   

 
Q: Imagine Java didn’t have a multiplication function. Write a program that asks the user to enter two whole numbers a and b and outputs ab (a to the power of b). Your program should use a loop within a loop.
 
This exercise has taken two weeks of puzzling out how to achieve the task given the requirements / constraints. The answer provided within the course notes is detailed below, but it’s not correct. If you use this code and input, say, 3 and 3 as the a and b variables, you get the answer 64. 33 is 27, not 64.
 
CODE: exponAdd1.java

//exponentiation by addition
import java.util.Scanner;
class exponAdd1
{
    
public static void main(String[] args)
    {
        
//System.out.println();
        //System.out.println("Raising powers by addition");
        //System.out.println();
        //input
        Scanner in = new Scanner(System.in);
        
System.out.print("Enter the two numbers to exponentiate? ");
        
int m = in.nextInt();
        
int n = in.nextInt();   
        
//calculation and printing
        int answer=1;
         
for (int j=0j<nj++)
                {
                
int total=0;
                
for (int i=0i<mi++)
                    {
                        
total=total+answer;
                        
answer=total;
                    }
                }       
            
System.out.println(m + " to the power of " + n
            + 
" = " + answer);
            
System.out.println();
    }
}   

 
So, what is the answer? Well, the only way I have found of doing this (so far) is to use a loop for each power of the base integer. So, the first loop, squares the number (multiplies the number by itself). The next loop effectively squares the result of the first loop by itself, creating the cube. Using this method, you would need (b-1) loops to give the correct answer. I’m sure there is another way of doing this, but given limited time and the remainder of the course to study, this is where I am going to leave this problem for now. Code for squaring and cubing a number shown below.
 
CODE: exponAdd.java

//exponentiation by addition
import java.util.Scanner;
class exponAdd
{
    
public static void main(String[] args)
    {
        
System.out.println();
        
System.out.println("Raising powers by addition");
        
System.out.println();
        
//input
        Scanner in = new Scanner(System.in);
        
System.out.print("Enter integer a> ");
        
int a = in.nextInt();
        
System.out.println();
    
        
//a routine that squares a (multiplies a by itself)
            int sum1=0;
            
for (int i=0i<ai++)
                {
                    
sum1=sum1+a;
                }                                       
        
//a routine that cubes a (multiplies a by itself three times)
            int sum3=0;
            
for (int j=0j<aj++)
                {
                    
int sum2=0;
                        
for (int i=0i<ai++)
                            {
                                
sum2=sum2+a;
                            }
                    
sum3=sum3+sum2;
                }
            
System.out.println("a squared is " + sum1);
            
System.out.println("a cubed is " + sum3);
            
System.out.println();
    }
}   

 
Q: Modify the code below using a nested loop to draw both the big hand and small hand of an analogue clock.
 
CODE: clock.java

import element.*;
public class clock
{
    
public static void main(String args[])
    {
        
int bighandSize=30windowSize=300origX=100origY=100;
        
double angle=Math.PI*3/2;
        
DrawingWindow d = new DrawingWindow(windowSizewindowSize);
        
while (true)
        {
            
d.paintMode();
            
d.moveTo(origXorigY);
            
d.lineTo((int)Math.round(origX+bighandSize*Math.cos(angle)),
                    (
int)Math.round(origY+bighandSize*Math.sin(angle)));
            
d.awaitMouseClick();
            
d.invertMode();
            
d.moveTo(origX,origY);
            
d.lineTo((int)Math.round(origX+bighandSize*Math.cos(angle)),
                    (
int)Math.round(origY+bighandSize*Math.sin(angle)));
            
angle+=Math.PI/30;
        }
    }
}

 
I really struggled with this in the time I had available. Makes sense when I look through the code below, although the answer here is directly lifted from the course notes (©UOL). I was too busy trying to move the hour hand a small amount for every increment in the minute hand which is where I failed on this question as it becomes very difficult to do this using two loops (but I’m sure, not impossible given enough time to consider the problem).
 
Note: the expression (int)Math.round(... is called type casting because we are telling Java to consider the output of the Math.round() method an integer and not a long which is the output type of this method. We have to do this because the method lineTo() will only accept integer type variables as inputs.
 
CODE: bigClock.java

import element.*;
public class bigClock
{
    
public static void main(String args[])
    {
        
int bigHandSize=100smallHandSize=50windowSize=300,
        
origX=150origY=150;
        
double smallAngle=Math.PI*3/2;
        
double bigAngle=Math.PI*3/2;
        
DrawingWindow d = new DrawingWindow(windowSizewindowSize);
        
int hour=0;
        
while (true)
        {
            
d.paintMode();
            
d.moveTo(origXorigY);
            
d.lineTo((int)Math.round(origX+smallHandSize
            *
Math.cos(smallAngle)),
                    (
int)Math.round(origY+smallHandSize
                    *
Math.sin(smallAngle)));
            
int min=0;
            
while(min<60)
            {
                
d.paintMode();
                
d.moveTo(origXorigY);
                
d.lineTo((int)Math.round(origX+bigHandSize
                *
Math.cos(bigAngle)),
                        (
int)Math.round(origY+bigHandSize
                        *
Math.sin(bigAngle)));
                
d.awaitMouseClick();
                
d.invertMode();
                
d.moveTo(origXorigY);
                
d.lineTo((int)Math.round(origX+bigHandSize
                        *
Math.cos(bigAngle)),
                        (
int)Math.round(origY+bigHandSize
                        *
Math.sin(bigAngle)));
                
if (hour*5==min//redraw the small hand
                                 //when the big hand goes past
                {
                    
d.paintMode();
                    
d.moveTo(origXorigY);
                    
d.lineTo((int)Math.round(origX+smallHandSize
                            *
Math.cos(smallAngle)),
                            (
int)Math.round(origY+smallHandSize
                            *
Math.sin(smallAngle)));
                }           
                
bigAngle+=Math.PI/30;
                
min++;
            }
            
d.invertMode();
            
d.moveTo(origX,origY);
            
d.lineTo((int)Math.round(origX+smallHandSize
            *
Math.cos(smallAngle)),
                    (
int)Math.round(origY+smallHandSize
                    *
Math.sin(smallAngle)));
            
smallAngle+=Math.PI/6;
            
hour=(hour+1)%12;
        }
    }
}

LEARNING OBJECTIVES

1. Learn how to declare and initialise an array.

To declare an array we use closed square brackets after the variable type and before the array name. So, for instance, a regular integer variable would be declared thus:

int a;

An array is declared thus:

int [] a;

An array is initialised by assigning a storage limit to the array by the following code:

a = new int [10];

Where [10] is the number of storage cells [elements] within the array.

We can assign a value to an array element with the following code:

a[2] = 5;

In this case we are assigning the value 5 to the 3rd element of the array (all arrays start with element [0]).

2. Learn how to use for loops to process arrays.

We can use for loops to process arrays rather than assigning a value to each element a line of code at a time. To do this, we set up a for loop where the guard condition allows the program to loop the same number of times as there are elements in the array and the variable within the for loop specifies the element to be assigned. An example is shown below:

for (int i=0; i  { int [i] a = 2; }

This would assign the number 2 to elements [0], [1], [2], [3] and [4] of array a.

3. Learn how to deal with array index out of bounds exceptions.

If you try to assign a value to an element of an array that has not been declared and initialised, a run-time error in Java will be caused called ArrayIndexOutOfBoundsException. We need to be careful to ensure that a for loop doesn’t exceed the number of elements within an array to ensure this error does not occur.

EXERCISES

Q: Write a program that reverses the order of the numbers input by a user and also asks the user how many numbers they will input at the beginning of the routine.

CODE: ReverseTenNewInput.java

import java.util.Scanner;
class ReverseTenNewInput
{
    
public static void main(String[] args)
    {
        
Scanner in = new Scanner(System.in);
        
System.out.println("How many numbers will you enter?");
        
int num = in.nextInt();
        
System.out.println("Enter "+num+" Numbers>");
        
int[] a;
        
a = new int[num];
        
for (int i = 0i<numi++)
        {
            
a[i] = in.nextInt();
        } 
        
System.out.println("reverse order is ");
        
for (int i = num-1i>=0i--)
        {
            
System.out.println(a[i]);   
        }
        
    }
}

 
Q: Rewrite the following code which determines the largest number input by a user but instead, use an array.

CODE: LargestNew.java

import java.util.Scanner;
class LargestNew
{
    
public static void main(String[] args)
    {
        
Scanner in = new Scanner(System.in);
        
System.out.print("How many numbers will you enter? ");
        
int n = in.nextInt();
        
System.out.println("Enter "+n+" numbers ");
        
int x = in.nextInt();
        
int largest=x;
        
for(int i=0i<(n-1); i++)
        {
            
x = in.nextInt();
            
if (x>largestlargest=x;
        }
        
System.out.println("largest is " + largest);
    }
}

 
Rewritten using an array.
 
CODE: LargestNewArray.java

import java.util.Scanner;
class LargestNewArray
{
    
public static void main(String[] args)
    {
        
Scanner in = new Scanner(System.in);
        
System.out.print("How many numbers will you enter? ");
        
int n = in.nextInt();
        
int [] store;
        
int largest=0;
        
store = new int [n];
        
System.out.println("Enter "+n+" numbers ");
        
for (int i=0i<ni++)
        {
            
int x = in.nextInt();
            
store [i] = x;
        }
        
for (int i=0i<ni++)
        {
            
if (store [i]>largestlargest=store [i];
        }
        
System.out.println("largest is " + largest);
    }
}

 
Q: Amend the following code to ensure the program behaves reasonably when a user enters 0 at the first input.
 
CODE: Input1New.java

import java.util.Scanner;
class Input1New
{
    
public static void main(String[] args)
    {
        
Scanner in = new Scanner(System.in);
        
System.out.print("How many numbers do you want to enter? ");
        
int k = in.nextInt();
                
int [] num = new int[k];
        
System.out.println("Now type in the numbers ");
        
for (int i=0i<ki++) num[i] = in.nextInt();
        
for (int i=0i<ki++) System.out.println(num[i]);
    }
}

 
Code above amended to deal with a 0 input from the user.
 
CODE: Input1NewAmended.java

import java.util.Scanner;
class Input1NewAmended
{
    
public static void main(String[] args)
    {
        
Scanner in = new Scanner(System.in);
        
System.out.print("How many numbers do you want to enter? ");
        
int k = in.nextInt();
        
while (k==0
            {
                
System.out.println("You've got to enter at least one!");
                
System.out.println("Try again!");
                
k = in.nextInt();
            }
        
int [] num = new int[k];
        
System.out.println("Now type in the numbers ");
        
for (int i=0i<ki++) num[i] = in.nextInt();
        
for (int i=0i<ki++) System.out.println(num[i]);
    }
}

 
Q: Write a program which reads some numbers into an array and prints out the largest, the smallest, the sum and the average.
 
Previous exercises involved writing a program that utilised an array to work out the largest number entered by the user. Code for smallest, sum and average shown below.
 
CODE: SmallestNewArray.java

import java.util.Scanner;
class SmallestNewArray
{
    
public static void main(String[] args)
    {
        
Scanner in = new Scanner(System.in);
        
System.out.print("How many numbers will you enter? ");
        
int n = in.nextInt();
        
int [] store;
        
int smallest;
        
store = new int [n];
        
System.out.println("Enter "+n+" numbers ");
        
int x = in.nextInt();
        
smallest = x;
        
store [0] = x;
        
for (int i=1i<ni++)
        {
            
x = in.nextInt();
            
store [i] = x;
        }
        
for (int i=1i<ni++)
        {
            
if (store [i] < smallestsmallest = store [i];
        }
        
System.out.println("smallest is " + smallest);
    }
}

 
CODE: SumNewArray.java

import java.util.Scanner;
class SumNewArray
{
    
public static void main(String[] args)
    {
        
Scanner in = new Scanner(System.in);
        
System.out.print("How many numbers will you enter? ");
        
int n = in.nextInt();
        
int [] store;
        
store = new int [n];
        
int sum=0;
        
System.out.println("Enter "+n+" numbers ");
        
int x;
        
for (int i=0i<ni++)
        {
            
x = in.nextInt();
            
store [i] = x;
        }
        
for (int i=0i<ni++)
        {
            
sum = sum + store [i];
        }
        
System.out.println("sum is " + sum);
    }
}

 
CODE: AverageNewArray.java

import java.util.Scanner;
class AverageNewArray
{
    
public static void main(String[] args)
    {
        
Scanner in = new Scanner(System.in);
        
System.out.print("How many numbers will you enter? ");
        
int n = in.nextInt();
        
int [] store;
        
store = new int [n];
        
double sum=0.0;
        
System.out.println("Enter "+n+" numbers ");
        
int x;
        
for (int i=0i<ni++)
        {
            
x = in.nextInt();
            
store [i] = x;
        }
        
for (int i=0i<ni++)
        {
            
sum = sum + store [i];
        }
        
        
double average = sum / n;
        
System.out.println("sum is " + sum);
        
System.out.println("n is " + n);        
        
System.out.println("average is " + average);
    }
}

 
Q: Write a program where the user types in a number of strings which are stored in an array of strings and then the program prints out all the longest strings entered by the user.
 
CODE: LongestString.java

import java.util.Scanner;
class LongestString
{
    
public static void main(String[] args)
    {
        
Scanner in = new Scanner(System.in);
        
String [] words;
        
System.out.println("How many strings will you input? ");
        
int num = in.nextInt();
        
words = new String[num];
        
System.out.println("Enter " + num + " strings> ");
        
words[0] = in.nextLine(); //added in to solve loop problem
        //for some reason following only loops num-1?!?
        for (int i=0i<numi++)
        {
            
words[i] = in.nextLine();
        }
        
for (int i=0i<numi++)
        {
            
System.out.println("String "i + " was " + words[i]);
        }
        
int [ ] lengthWords;
        
lengthWords = new int[num];
        
for (int i=0i<numi++)
        {
            
//length() method works out the number of chars in string
            lengthWords[i] = words[i].length();
        }
        
int max = 0;    //stores when a string is longer than previously
                        //stored
        int [] counter//used to help deal with strings of equal length
        counter = new int[num];
        
//sets counter array to zero to begin with
        for (int i=0i<numi++)
        {
            
counter[i]=0;
        }
        
for (int i=0i<numi++)
        {
            
//figures out which strings are longest and stores in max
            if(lengthWords[i]>=max)
            {
                
max = lengthWords[i];
            }
        }
        
for (int i=0i<numi++)
        {
            
//checks to see more than one string meets max string length
            //and sets a flag in the counter array
            if(lengthWords[i]==max)
            {
                
counter[i]=1;
            }
        }
        
for (int i=0i<numi++)
        {   
            
if (counter[i]==1)
            
//prints out all those string lengths with max flag set
            {
                
System.out.println("Longest string/s is/are " 
                + 
words[i]);
            }
        }
    }
}

 
Q: Write a program where the user types in a number of Strings stored in an array of Strings and then the program prints out all the Strings that have the most occurrences of the character ‘a’.
 
A tricky one this for someone at this stage of the course, but not impossible. Here’s my solution below.
 
CODE: MostCharA.java

import java.util.Scanner;
class MostCharA
{
    
public static void main(String[] args)
    {
        
Scanner in = new Scanner(System.in);
        
//string array to store words input
        String [] words;
        
System.out.println("How many strings will you input? ");
        
int num = in.nextInt();     //num = number of words input
        
        
//initialise words[]array here because num not declared before
        words = new String[num];
        
        
System.out.println("Enter " + num + " strings> ");
        
        
words[0] = in.nextLine();   //added in this line 
                                    //solve loop problem below
                                    //force the first input
                                    //to be stored
        //for some reason the following only loops num-1?!?
        //this loops captures all the words input into an array
        for (int i=0i<numi++)
        {
            
words[i] = in.nextLine();
        }
        
        
//now we need to work out the length of each word and
        //store these lengths in another array called lengthWords[]
        int [ ] lengthWords;
        
lengthWords = new int[num]; //number of elements is # words
        for (int i=0i<numi++)
        {
            
//length() method works out the number of chars in each word
            //of the array
            lengthWords[i] = words[i].length();
        }
        
        
//now we need to figure out the max length of the words
        //input to give the upper limit for array letters[]
        //and oneLetterString[] defined and used below
        
        
int maxLetters = 0;
        
for (int i=0i<numi++)
        {
            
//figures out the maximum number of chars per word and
            //stores in variable maxLetters
            if(lengthWords[i]>=maxLetters)
            {
                
maxLetters = lengthWords[i];
            }
        }
        
        
//because java is a pain in the *$@# with variable types we
        //now need to create two new arrays.
        //one array letters[] converts the words[] array from a
        //string array into a character array so we can dissect the
        //words input into their individual characters.
        //the other array oneLetterString[] converts the character
        //array back into a string array but now holding the
        //individual letters which make up each word as strings!!
        //nightmare!        

        
char [] letters;
    
        
String [] oneLetterString;
        
        
int countA=0;   //this variable counts the 'a's in each word
        int [] numA;    //array to store number of 'a's in each word
        
        
letters = new char[maxLetters]; //limit of array, number
                                        //of letters in longest
                                        //word input
        oneLetterString = new String[maxLetters];
                                        
//limit of array as above
                                        
        
numA = new int[num];            //one entry per word, hence num
                                        //is the upper limit of array
        
        
//we use a nested loop here, the outer loop cycles through the
        //number of words input at the beginning of the routine
        for (int j=0j<numj++)
        {
            
//the inner loop cycles through the number of letters in
            //each word input and compares to see how many 'a's exist
            //in each word
            for (int i=0i<lengthWords[j]; i++)
            {
                
letters[i] = words[j].charAt(i);
                
oneLetterString[i] = Character.toString(letters[i]);
                
//the following statement is true if there is a match
                if (oneLetterString[i].compareTo("a")==0)
            {
            
//increase the count of the number of 'a's
            countA++;
            }
        }
        
//store the total number of 'a's in the word into the array
        //that records the number of 'a's per work
        numA[j] = countA;
        
//reset countA to zero ready for the next word
        countA = 0;
        }       
        
int max = 0;    //used to figure out which string has most 'a's
        int [] counter//used to help deal with strings 
                        //with equal number of 'a's
        counter = new int[num];
        
//the following sets the counter array to zero to begin with
        //across all elements
        for (int i=0i<numi++)
        {
            
counter[i]=0;
        }
        
//figures out which strings have most 'a' and stores in max
        for (int i=0i<numi++)
        {
            
if(numA[i]>=max)
            {
                
max = numA[i];
            }
        }
        
for (int i=0i<numi++)
        {
            
//checks to see if more one string meets max 
            //string length and sets a flag in the 
            //counter array
            if(numA[i]==max)
            {
                
counter[i]=1;
            }
        }
        
for (int i=0i<numi++)
        {   
            
if (counter[i]==1)
            
//prints out all those string lengths with max flag set
            {
                
System.out.println("String(s) with most 'a's is/are '" 
                + 
words[i] + "' which has " + numA[i] + " 'a's.");
            }
        }       
    }
}

LEARNING OBJECTIVES

1. Explain the difference between static and non-static methods.

If a method does not include the word ‘static’ in its definition then it is known as a non-static or instance method. Each instance method needs to be called using dot notation. What does that mean? Essentially, if a method is defined public int x(int) within a class called y then every time we call x we have to do so in the form z.x(e) where z is an expression of type y (that is, it evaluates to an object of type y) and e is an expression of type int. I really hope this is explained better later on in the course!

2. Explain the difference between the use of void and non-void methods.

A method that can be used as an expression (i.e. can appear after an = sign) is called non-void. This means that the method returns a value when it is executed of a type defined in its signature. A void method does not have a return type, or more accurately has a return type void.

3. Investigate some of the methods of the class java.lang.String.

You can find the full definition of the method java.lang.String on the Oracle website.

The method length() returns the number of characters in a string and its signature is String.length(). So "jon".length() will return the value 3.

The method charAt() returns the character at a particular position in the String being evaluated and has the signature String.charAt(int).

The method compareTo() compares two strings to see if they are the same and returns zero if they are the same (amongst other lexicographical returns).

4. Explain what we mean by method overloading.

When one method name exists that has two different signatures (so it performs different functions) we say we are overloading the method. If a method exists example(int) and another method exists example(int, String) we would say the method example() is overloaded. This is perfectly valid in Java.

5. Explain what we mean by type-checking.

We need to make sure that the variables and expressions that we are using when we call a method are of the right type. We can do that either by checking the signature of the method with the online documentation that is provided with Java or we can let the compiler throw an error when we get it wrong and adjust as we code.

EXERCISES

Q: Write a program which asks the user to enter 3 strings and then prints them out in reverse dictionary order.

So this took some time and the solution is not the same as in the course notes because still getting my head around if...else statements. This code works by going through all possible logical combinations of the 3 words entered and figuring out which order they must appear in using the compareTo() method.

CODE: ReverseDictionaryOrder.java


import java.util.Scanner;
class ReverseDictionaryOrder
{
    
public static void main(String[] args)
    {
        
Scanner in = new Scanner(System.in);
        
System.out.println("Please enter the three strings> ");
        
System.out.println();   //extra space
        String[] input;
        
input = new String[3];
        
String first="";
        
String second="";
        
String third="";
        
for (int i=0i<3i++)
        {
            
input[i] = in.nextLine();
        }
        
        
//need to create all permutations of the words
        //for a logical comparison using compareTo
        
        
int perm01perm02perm10perm12perm20perm21;
        
perm01 = input[0].compareTo(input[1]);
        
perm02 = input[0].compareTo(input[2]);
        
perm10 = input[1].compareTo(input[0]);
        
perm12 = input[1].compareTo(input[2]);
        
perm20 = input[2].compareTo(input[0]);
        
perm21 = input[2].compareTo(input[1]);
        
        
//the following logic does my head in
        //to figure it out right out a truth table
        
        
//Test for duplicates - words 0, 1 and 2 are the same
        if (perm01==0 && perm02==0)
        {
            
first = input[0];
            
second = input[1];
            
third = input[2];
        }
        
        
//Test for duplicates - 2 the same
        if (perm01==0//words 0 and 1 are the same
        {
            
if (perm02<0// word 0 (and 1) precedes word 2
            {
                
first = input[0];
                
second = input[1];
                
third = input[2];
            }
            
else        // if not word 2 precedes word 0 and 1
            {
                
first = input[2];
                
second = input[0];
                
third = input[1];
            }
        }
            
        
if (perm12==0//word 1 and 2 are the same
        {
            
if (perm01<0)   // word 0 precedes word 1 (and 2)
            {
                
first = input[0];
                
second = input[1];
                
third = input[2];
            }
            
else            // if not word 1 and 2 precedes 0
            {   
                
first = input[1];
                
second = input[2];
                
third = input[0];
            }
        }
        
        
if (perm02==0//word 0 and 2 are the same
        {
            
if (perm01<0// word 0 (and 2) precedes 1
            {
                
first = input[0];
                
second = input[2];
                
third = input[1];
            }
            
else
            {
                
first = input[1];
                
second = input[0];
                
third = input[2];
            }
        }
        
        
if (!(perm01==0 && perm02==0) && !(perm01==0
            && !(
perm12==0) && !(perm02==0))
        {
            
//Clumsy testing of all combinations - better with else...
            //word 0 precedes word 1 and 2
            //word 1 precedes word 2
            if (perm01<0 && perm02<0 && perm12<0)       
            {
                
first = input[0];
                
second = input[1];
                
third = input[2];   
            }
            
            
//word 0 precedes word 1 and 2
            //word 2 precedes word 1
            if (perm01<0 && perm02<0 && perm21<0)       
            {
                
first = input[0];
                
second = input[2];
                
third = input[1];   
            }
            
            
//word 1 precedes word 0 and 2
            //word 0 precedes word 2
            
            
if (perm10<0 && perm12<0 && perm02<0)       
            {
                
first = input[1];
                
second = input[0];
                
third = input[2];   
            }
            
            
//word 1 precedes word 0 and 2
            //word 2 precedes word 0
            
            
if (perm10<0 && perm12<0 && perm20<0)       
            {
                
first = input[1];
                
second = input[2];
                
third = input[0];   
            }
            
            
//word 2 precedes word 0 and 1
            //word 0 precedes word 1
            
            
if (perm20<0 && perm21<0 && perm01<0)       
            {
                
first = input[2];
                
second = input[0];
                
third = input[1];   
            }
            
            
//word 2 precedes word 0 and 1
            //word 1 precedes word 0
            
            
if (perm20<0 && perm21<0 && perm10<0)       
            {
                
first = input[2];
                
second = input[1];
                
third = input[0];   
            }
        
        }
            
            
System.out.println(third + " " + second + " " + first);
        
    }
}

 
Q: For each of the following expressions say whether it type checks correctly and, if possible, give its value. Write a program if necessary.

(i) Math.abs("hello")
 
No – this does not type check correctly, as the signature of Math.abs() expects type double not String.
 
(ii) Math.abs("hello".length())
 
Yes – this does type check correctly, as the signature of Math.abs() expects type double of which a type int is valid. The output of method length() is of type int.
 
(iii) Math.abs("hello".length())+5)
 
Yes – this does type check correctly for the same reasons as (ii) above.
 
(iv) "fruit".charAt(Math.abs("hello".length())-3)
 
Yes – this does type check correctly for the same reasons as (ii) above.
 
(v) "boy".compareTo(6)
 
No – this does not type check correctly as the input type for compareTo() is String.
 
(vi) "boy".compareTo("girl")
 
Yes – this type checks correctly as the input type of compareTo() is String.
 
(vii) "boy".compareTo("6")
 
Yes – this type checks correctly for the same reason as (vi).
 
(viii) "boy".compareTo("6")+17
 
Yes – this type checks correctly as the output type of compareTo is int.
 
(ix) "boy".replace('b',"soup".charAt(0))
 
Yes – this type checks correctly. The input type of replace() is char for both arguments and outputs a string. The output type of charAt() is char and the input type is int.
 
(x) ("boy".replace('b',"soup".charAt(0))).length()
 
Yes – this type checks correctly. The output type of replace() is string which is the input type of length().
 
Q: Write programs to investigate the following methods and describe their behaviour.
 
(a) String substring(int)

 
The substring(int) method creates a new string by starting from the character specified in the signature and ignoring characters before it.
 
(b) String substring(int, int)
 
The substring(int, int) method creates a new string by ignoring characters prior to the first argument and after the second argument.
 
(c) String replace(char, char)
 
The replace(char, char) method replaces all first character argument matches within a string with the second character argument, like a find and replace within an application.
 
Q: Write a program that asks the user to enter a string and then outputs the number of occurrences of the character ‘a’ in the String the user entered. For example, if the user entered “hello” the output would be 0, but if the user entered “abracadabra’, the answer would be 5.
 
CODE: findanA.java

import java.util.Scanner;
class findanA
{
    
public static void main(String[] args)
    {
        
Scanner in = new Scanner(System.in);
        
System.out.println("Enter your string> ");
        
String input = in.nextLine();
        
//figure out length of input string
        int len = input.length();
        
//set up a variable to count the num of 'a's
        int acount=0;
        
for (int i=0i<leni++)
        {
            
//compare characters within the string
            if (Character.toString
            (
input.charAt(i)).compareTo("a") == 0)
            {
                
//if there is an 'a' increase count
                acount++;
            }
        }   
        
//print out the count of 'a's
        System.out.println(acount); 
    }
}

 
Q: For each method in the class Integer give its signature.
 
There seems very little point recreating a page on the oracle.com site which itemises the Integer class. So all signatures can be found here.

LEARNING OUTCOMES

1. Contrast the approaches of using line and shape elements with the approach of manipulating individual pixels in creating images

Whilst pixel manipulation is a slow way to do things compared to Processing’s built-in shape drawing methods it gives us complete control over the screen.

2. Describe Conway’s Game of Life

The Game of Life was invented by John Conway in 1970. He was a British mathematician and devised a simple set of rules which are applied to a 2-dimensional pixel grid which give rise to complex patterns of behaviour such as motion, growth and death.

The rules that Conway came up with are:

  • Any live cell (pixel) with fewer than two live neighbours dies, as if by loneliness.
  • Any live pixel with more than three live neighbours dies, as if by over-crowding.
  • Any live pixel with two or three live neighbours lives, unchanged to the next generation.
  • Any dead cell with exactly three live neighbours comes to life.

3. Develop one- and two-dimensional cellular automata that perform according to certain rules.
 
CODE: game_of_life_replicating_zoomed

int y=1;    //initial row
PImage g1;  //next generation pixels stored in an image
void setup()
{
  size(64 ,64);
  g1 = new PImage(width, height);    //new generation
  background(0);
  
  /* remove these comments if you want to use glider
  
  //initial conditions of the two gliders
  int w = width/2, h=height/2;
  set(w-1, h-1, ~0); set(w, h-1, ~0);
  set(w+1, h-1, ~0); set(w-1, h, ~0);
  set(w, h+1, ~0);
  w=width/3; h=height/3;
  set(w-1, h-1, ~0); set(w, h-1, ~0);
  set(w+1, h-1, ~0); set(w-1, h, ~0);
  set(w, h+1, ~0);
  
  */
  
  //initial conditions for self-replicating pattern
  int w = width/2, h=height/2;
  set (w-2, h-2, ~0);
  set (w-2, h-1, ~0);
  set (w-2, h+2, ~0);
  set (w-1, h-2, ~0);
  set (w-1, h+1, ~0);
  set (w, h-2, ~0);
  set (w, h+1, ~0);
  set (w, h+2, ~0);
  set (w+1, h, ~0);
  set (w+2, h-2, ~0);
  set (w+2, h, ~0);
  set (w+2, h+1, ~0);
  set (w+2, h+2, ~0);
  
}
void draw()      //check entire screen in 3x3 grids
{
  for (int x=1; x<width; x++)
  {
    int sum=0;
    for (int xx=-1; xx<2; xx++)
      for (int yy=-1; yy<2; yy++)
        if(!(xx==0 && yy==0))
          sum+=(get(x+xx, y+yy)&1);
    if(((get(x,y)&1)==1))
      if(sum==2 || sum==3)
      
        {
          g1.set(x, y, ~0);
          g1.set(x+1, y, ~0);
          g1.set(x+2, y, ~0);
          g1.set(x, y+1, ~0);
          g1.set(x, y+2, ~0);
          g1.set(x+1, y+1, ~0);
          g1.set(x+1, y+2, ~0);
          g1.set(x+2, y+1, ~0);
          g1.set(x+2, y+2, ~0);

        }          
 
            else
            
               {
                g1.set(x, y, (~0)<<24);
                g1.set(x+1, y, (~0)<<24);
                g1.set(x+2, y, (~0)<<24);
                g1.set(x, y+1, (~0)<<24);
                g1.set(x, y+2, (~0)<<24);
                g1.set(x+1, y+1, (~0)<<24);
                g1.set(x+1, y+2, (~0)<<24);
                g1.set(x+2, y+1, (~0)<<24);
                g1.set(x+2, y+2, (~0)<<24);

               }                         
          
                else
                 if(sum==3)
                   
                     {
                      g1.set(x, y, ~0);
                      g1.set(x+1, y, ~0);
                      g1.set(x+2, y, ~0);
                      g1.set(x, y+1, ~0);
                      g1.set(x, y+2, ~0);
                      g1.set(x+1, y+1, ~0);
                      g1.set(x+1, y+2, ~0);
                      g1.set(x+2, y+1, ~0);
                      g1.set(x+2, y+2, ~0);

                      }       
              
  }
  if(++y>height)
  {
    // set(0,0,g1);    //put next generation on the screen
    image(g1, 0, 0);
    
    y=1;  //begin again
  }
}

CODE: rule_automaton

int y;
int rule=110;
void setup()
{
  size(256,256,P3D);
  background(0);
  set(width/2,0,~0);
}
void draw()
{
  for (int x=1; x<width-1; x++)
  {
    int pix1 = (get(x-1,y)&1)<<2;  //100
    int pix2 = (get(x,y)&1)<<1;    //010
    int pix3 = get(x+1,y)&1;     //001
    int bits=pix1+pix2+pix3;
    if((rule&(1<<(bits)))>0)       //test pattern in rule
      set(x,y+1, ~0);              //set next row if true
  }
  if (++y>height)
  return;
}

 

EXERCISES

Q: In this chapter, you saw a one-dimensional cellular automaton and a two-dimensional cellular automaton. What is the difference between these? What would a three-dimensional cellular automaton do? Can you find or create examples of one? Is it possible to have 4-dimensional cellular automaton?

A one dimensional cellular automata is one where the rules for the next generation of the automata is defined in terms of a line or just a single axis if we are considering the output in terms of a graph. Only the cells before and after the cell in the line to be assessed are considered in the rule criteria for the next line. A two dimensional cellular automata consider the cells above and below the cell to be assessed, as though on a flat plane, so in total each cell has 8 neighbours (left, top-left, top, top-right, right, bottom-right, bottom, bottom-left). You can consider two-dimensional automata as assessing both the x and y axes of the graph in the rule conditions. A three-dimensional automata would assess the x, y and z axes in its rule conditions as though a solid object, a 4-dimensional to include yet a further axis (perhaps a time component). It is possible to have as many dimensions as you like as long as it is a finite whole number.

Q: The examples in this chapter use a parameter, P3D, in the size() method. What is this parameter and what is it doing? What happens if you leave it out?

The P3D parameter in the size() method instructs Processing to use a 3D rendering system because by default, Processing only renders in two dimensions. P3D is the default Processing 3D render engine, it is the simplest and most compatible and requires no additional libraries to be imported to the program. In these specific examples, P3D is allowing the overlaying of images on top of one another.

Q: This chapter focussed on the use of pixel manipulation to create images. What aspects of a pixel can be manipulated (changed)?

In Processing, and Java, the colour value of a pixel can be manipulated. Each pixel is represented by a 32 bit (4 byte) integer. Each byte controls the following: the Alpha channel and the Red, Green and Blue colour channels respectively. When all colour channels have the same value we see shades of grey. When they are all 1s we see white pixels and when they are all zeros we see all black. The Alpha channel controls the degree of opacity of each pixel (the opposite of its transparentness). With a value of 255 (11111111) the pixel is completely opaque – a value of zero, completely transparent.

Q: Modify text book examples to include colour rather than greyscale shading. You should bring a creative component as well as a technical component to the exercise.

Exercise-9.2-Color
 
CODE: image_bits_color

int y;
int c=~0>>8;  //alpha mask
color col= color(45, 210, 45);
void setup()
{
  size(256,256,P3D);
  background(0);
  set(width/2,0,col);
}
void draw()
{
  for(int x=1; x<width-1; x++)
    set(x, y+1, (get(x-1,y)&c ^ get(x,y)&c ^ get(x+1,y)&c) | ~c);
   if(++y>height) y=0;
}

CODE: rule_automaton_color

int y;
int r = 100;
int g = 50;
int b = 25;
int rule=62;
void setup()
{
  size(256,256,P3D);
  background(0);
  set(width/2,0,~0);
}
void draw()
{
  for (int x=1; x<width-1; x++)
  {
    color c = color (r,g,b);
    int pix1 = (get(x-1,y)&1)<<2;  //100
    int pix2 = (get(x,y)&1)<<1;    //010
    int pix3 = get(x+1,y)&1;     //001
    int bits=pix1+pix2+pix3;
    if((rule&(1<<(bits)))>0)    //test pattern in rule
      {
        set(x,y+1,~c);      //set next row if true
        if (g<255)
          {g++;}
        else
        {g=0;}
        if (r<255)
        r++;
        else
        r=0;
        if (b<255)
        b++;
        else
        b=0;
      }
}
  if (++y>height)
  return;
}