Java Course 9: Test Yourself

Write programs to do the following

  1. Prompt the user to enter the length and width of a square. Output the area of the square.
  2. Prompt the user to enter a test score. Output their grade: Under 100 – Fail, Under 120 Pass, Under 130 Merit, 130+ Distinction
  3. Use a for loop to print out the following sequence: 12, 15, 18, 21, 24, 27
  4. Use a for loop to print out the first 8 square numbers: 1,4,9,16,25,36,49,64
  5. Make a counting program. Use a do while loop to keep asking “Another?” until the user enters “n”. Output the number of times the loop repeated
  6. Create a file called names.txt containing the names John, Paul, George and Ringo. Write a program the reads in the text file and prints out the data
  7. Create a string array containing the four seasons: spring, summer, autumn and winter. Print out a random season

Extension

Write a program that prints out the verses of the song the Twelve Days of Christmas. You will get bonus marks for elegant coding.

On the first day of Christmas
my true love sent to me:
A Partridge in a Pear Tree

On the second day of Christmas
my true love sent to me:
2 Turtle Doves
and a Partridge in a Pear Tree

On the third day of Christmas
my true love sent to me:
3 French Hens
2 Turtle Doves
and a Partridge in a Pear Tree

.
.
.

On the first day of Christmas
my true love sent to me:
12 Drummers Drumming
11 Pipers Piping
10 Lords a Leaping
9 Ladies Dancing
8 Maids a Milking
7 Swans a Swimming
6 Geese a Laying
5 Golden Rings
4 Calling Birds
3 French Hens
2 Turtle Doves
and a Partridge in a Pear Tree

Java Course 8: Methods

Before you do this section, watch the videos here: https://www.dropbox.com/sh/v0xcqgjkia6brmm/AABRKcrZjwhkR1j14NsMcd4za?dl=0

Older programming languages distinguish between Functions and Procedures. Very simply, a function returns a value, a procedure does not.

Java rolls both of these into one concept: Methods. A method always has a return type. If the return type is void it is what an older language would call a procedure, otherwise it’s a function.

Here is an example method:

public void spoons (String s, int i)
Access TypeReturn TypeNameParameters
publicvoidspoons(String s, int i)

Two example Classes

public class Main {

    public static void main(String[] args)
    {
	Person p1 = new Person("Bloggs", "Joe");
	p1.setSex("M");

	Person p2 = new Person("Baker", "Jill");
	p2.setGender("F");

	p1.printPerson();
	p2.printPerson();
    }

}


public class Person {

     private String surname;
     private String forename;
     private String gender;     

    Person(String surname, String forename)
    {
	this.surname = surname;
	this.forename = forename;
    }

    public void setGender(String s)
    {
	if(!(s.equals("F")|s.equals("M")))
	{
	    System.out.println("Validation error!");
	} else
	{
	    sex = s;
	}
    }

    public void printPerson()
    {
	System.out.println(surname + " " + forename + " " + gender);
    }

}

Method Exercise: Progress Tracker

Write a class Pupil that will track pupils’ progress through a year. The class will store pupils’ grades as percentages.

  1. Add private member variables String forename, surname
  2. Add private member variables int target, autumn, spring, summer
  3. Add a constructor method that will accept the parameters forename, surname, target
  4. Test the constructor by adding the following pupils: Joe, Bloggs, 70 and Jill, Cooper, 75
  5. Add accessor methods to setAutumn(), setSpring(), setSummer()
  6. Add accessor methods to getAutumn(), getSpring(), getSummer()
  7. Add the following grades to Joe Bloggs:  Autumn 55, Spring 65, Summer 75
  8. Add the following grades to JIll Cooper:  Autumn 50, Spring 60, Summer 70
  9. Add a method average() to return a double showing the average percentage a pupil has. Print out Joe and Jill’s average scores
  10. Add a method progress() that will return a String saying whether the pupil is above target, on target or below target on the summer test.
  11. Check this method works on Joe and Jill
  12. Add a print() method that will print out the pupil’s details in a suitable format

Extension Work

  • Add a validation() method to check that grades entered lie between 1 and 100
  • Modify your average() method so it will return a correct average if only one or two grades have been entered so far
  • Add a static int variable aBound to record the grade A boundary.
  • Add the appropriate setters and getters to aBound
  • Set up a Pupil [] array in your Main class to handle your pupils
  • Add a save() method to your Pupil class that will write the pupil data to file

Java Course 7: Arrays

Iterate Through an Array

String [] day =    {"Monday", "Tuesday", "Wednesday", 
		    "Thursday", "Friday", "Saturday", "Sunday"}; 

for(int i = 0; i<day.length;i++)
{
    System.out.println(day[i]);
}

Random Element of Array

String [] day = {"Monday","Tuesday","Wednesday","Thursday",
"Friday","Saturday","Sunday"};
int d = (int)(Math.random()*7);
System.out.println(day[d]);

Splitting a String into Words

String s = "This is an example string";
String [] seperated = s.split("\\s+");
for (int i=0; i<seperated.length; i++)
{
	System.out.println(seperated[i]);
}

for each loops

String [] day =    {"Monday", "Tuesday", "Wednesday", 
		    "Thursday", "Friday", "Saturday", "Sunday"}; 

for(String s: day)
{
    System.out.println(s);
}

Exercise

  1. int [] numbers = {3,5,3,4,7,8}; Print out the second element of the array
  2. Make a String array of the months of the year. Print out all the months.
  3. Print out a random month of the year
  4. Create an int array recording the number of days in each month
  5. Print out all the months and the days in each month.
  6. int [] numbers = {3,5,5,4,8,8,10,2}; Print out the total of all the numbers in the array. Print out the average
  7. Make a string array with the words “First”; “Second”; “Third”; … “Twelfth”. Write a for loop to print out “On the First Day of Christmas,” “On the Second Day of Christmas” etc.
  8. Separate the following string using the “,” as a token. Print out all the elements. String s = “1,5,6,1,7,1,4,3,1,4,5,6,1,5,3,5,6,4,4,8”;

Extension

Paste the following code into your IDE, and then do the questions below.

String [] question = { "What is the capital of France?",
		       "What is the capital of Germany?",
		       "What is the capital of Spain?"};
String [] answer = {"Paris", "Berlin","Madrid"};

int score = 0;
Scanner scan = new Scanner(System.in);
String input;

for(int i= 0; i<3; i++)
{
     System.out.println(question[i]);
     input = scan.nextLine();
     if(input.equals(answer[i]))
     {
	 score++;
     }
}

System.out.println("You scored "+ score + " out of "+ question.length);
  1. Run the code to check it works
  2. Add some extra questions and answers. Check the code still works
  3. Add code to print out the correct answer if the user gets a question wrong
  4. Alter your code so that questions and answers are read in from text files

Java Course 6: while and do While Loops

Counting Down

int count = 10;
while (count>0)
{
    System.out.println(count);
    count = count - 1;
}
System.out.println("Lift off!");

Counting Objects

String colours = "red blue red blue blue blue blue red blue red blue "
		 + "red blue blue red blue blue blue red blue red red "
		 + "blue blue red red red red blue red blue red blue blue";


Scanner scan = new Scanner(colours);
int redcount = 0;

while (scan.hasNext()) {
    String s = scan.next();
    if (s.equals("red")) {
	redcount = redcount + 1;
    }
}
System.out.println("Number of reds " + redcount);

A Basic Question Loop

Scanner scan = new Scanner(System.in);
String answer;

do
{
    System.out.println("What's the capital of France?");
    answer = scan.nextLine(); 

}while (!answer.equals("Paris"));
 System.out.println("Correct!");

A Question Loop with a Count

Scanner scan = new Scanner(System.in);
String answer;
int count = 0;

do
{
    System.out.println("What's the capital of France?");
    answer = scan.nextLine();
    count = count + 1;

}while (!answer.equals("Paris"));
 System.out.println("Correct!");
 System.out.println("It took you " + count + " guesses");

A Question Loop with a Flag

Scanner scan = new Scanner(System.in);
int answer;
boolean isNotDone = true;

do
{
    System.out.println("Enter an Integer, 0 to end.");
    answer = scan.nextInt();
    System.out.println(answer + " squared = " + answer * answer);
    if (answer == 0)
    {
	isNotDone = false;
    }

}while (isNotDone);
 System.out.println("Done!");

A Question Loop with a Count and a Flag

Scanner scan = new Scanner(System.in);
String answer;
boolean isCorrect = false;
int count = 0;
do
{
    System.out.println("Enter the password");
    answer = scan.nextLine();
    if (answer.equals("Java"))
    {
	isCorrect = true;
    }
    count = count + 1;
 }while(!isCorrect & count <3 );


if (isCorrect)
{
    System.out.println("Correct password");
}
else
{
    System.out.println("Incorrect password");

Exercise

while Questions

  1. Use a while loop to print out the integers from 1 to 10
  2. Use a while loop to print out the even numbers from 2 to 20
  3. Use a while loop to print out the four times table
  4. Use a while loop to print out the five times table in the form “n x 5 = 5n”
  5. Use a while loop to print out the sequence 7,10,13,16,19,22,25
  6. Use a while loop to print out the sequence -0.3, -0.2, -0.1, 0, 0.1, 0.2
  7. Use a while loop to print out the sequence 64, 32, 16, 8, 4, 2, 1
  8. Use a while loop and Scanner to count how many heads and tails there are in the String below. (nb. you should carefully copy and paste the String into your program)

String coins = “head head tail head tail head head head tail head tail head tail head head head tail “+ “head tail head tail head tail head tail head tail tail tail head head head tail “+ “tail head tail head tail tail head head head tail tail tail head tail head head head tail “+ “head tail tail head tail head head head tail head tail head tail head head head head “+ “head tail head tail head tail head head head tail tail head tail head tail head head head head”;

  1. Write a code to find the number of times the word “never” appears in the following poem: I never saw a purple cow, I never hope to see one, but I can tell you anyhow, I’d rather see than be one.”
  2. Now search the Internet for the text to the poem “McCavity the Mystery Cat” Write code to count the number of times the word McCavity appears.

do while Questions

  1. Make the computer keep asking “Are we there yet?” until the answer yes is input.
  2. Ask the user the to guess a number between one and ten. Hard code the number 4 as an answer. The computer will print out how many guesses the user takes before they get the correct answer.
  3. Modify program 2 so that the computer chooses a random number as the answer.
  4. Write a higher lower game. Modify program 3. The computer thinks of a number between 1 and 100. The user tries to guess the number, and the computer tells the user if their answer is higher or lower. Whe then user guesses correctly, the computer congratulates the user and tells them how many guesses it took them.
  5. Wrtie a password checker. The user cannot proceed until they enter the correct password.
  6. Modify your password checker so that the user sees the message “Locked Out” if they fail to guess the password in three guesses.

Extension

The skeleton code below is intended to guess the number the end user is thinking of. The end user can enter yes if the computer guesses the answer, higher if the number is higher and lower otherwise. Copy the code into the IDE and complete it.

Scanner scan = new Scanner(System.in);
double num = Math.random()*100;
int ran = (int)num+1;
int guess = 50;
int high =100;
int low= 0;
String input = "";
boolean isCorrect = false;

do
{
    System.out.println("Is the number " + guess + "?");
    input = scan.nextLine();
    if(input.equals("yes"))
    {
	isCorrect = true;
    }
    else if(input.equals("higher") )
    {
	low = guess;
	guess = low + (int)(high-low)/2;
    }


}while(!isCorrect);

Java Course 5: for Loops

Print the numbers 1 to 9

(look very carefully at the semi colons below!)

for(int i= 1; i<10; i=i+1) {
    System.out.println(i);
}

Print the numbers 1 to 10

for(int i= 1; i<=10; i=i+1) {
    System.out.println(i);
}

Print the numbers 10 to 1

for(int i= 10 ; i>0; i=i-1) {
    System.out.println(i);
}

Prints the first ten squared numbers in the form “3 squared = 9”

for(int i =1; i<=10; i =i+1) {
    System.out.println(i+ " squared = "+ i*i);
}

Nested for loops

The following nested for loops print out the pattern triangle pattern below. Note the j<i condition in the second for loop and the use of print() and println().

for(int i = 0; i < 6; i++) {
	   for(int j = 0; j < i; j++) {
	       System.out.print("*");
	   }
	   System.out.println("");
}
*
**
***
****
*****

Exercise

Use for loops to print out the following:

  1. Numbers from 1 to 70 inclusive
  2. Numbers from 10 to -10 inclusive
  3. Odd numbers from 1 to 19 inclusive
  4. Even numbers from 10 to -20 inclusive
  5. The sequence 0.3, 0.4, 0.5, 0.6, 0.7
  6. The sequence 0.1, 0, -0.1, -0.2, -0.3
  7. The square numbers 1, 4, 9, 16, … 81, 100
  8. Five random integers between 1 and 10 inclusive
  9. All multiples of 3 up to 99
  10. The powers of 2 up to 28 (2, 4, 8, … 128, 256)

Nesting Loops

Use nested for loops to print out the following patterns

*
**
***
****
*****
******
*******
********
*********
*****
****
***
**
*
**
****
******
********
  1. 6!, pronounced 6 factorial, means 6x5x4x3x2x1. Write a program to print out the first 10 factorial numbers.
  2. Print out the times tables for 1 to 10. Print them out in the format “2 x 3 = 6”
  3. Print out a chess board grid using 1s and 0s e.g. 0 1 0 1 0 1 0 1, then 1 0 1 0 1 etc to make an 8×8 grid.

Extension

Print out the following patterns, either using nested for loops or some other way…

     *
    **
   ***
  ****
 *****
******
   *
  ***
 *****
*******
   *
  ***
 *****
*******
 *****
  ***
   *

Java Course 4: Selection

if statement

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

Operators

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

Examples

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

Questions

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

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

Extension

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

Java Course 3: Random Numbers and Rounding

Random Numbers

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

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

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

Rounding and Formatting Decimals

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

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

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

Sample Formats

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

Exercise: Fahrenheit to Celsius

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

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

Test Data

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

Java Course 2: Types

Integers

// declare variables
int x;
int y;

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

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

Casting and Converting

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

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

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

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

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

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

You can covert Double, Float etc to Strings similarly.

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

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

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

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

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

Exercise: operations on int and double

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

Good Practice

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

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

or

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

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

Java Course 1: Input Output

The basic Java program is called a class.  A class is much more than a program, you’ll see why as we go on.

Classes contain methods, which are a little like functions in other languages.  The first function to run is called main().  You will notice it is written

public void main(String [] args)

I’ll explain what those other words mean later on.

Every part of a java program is contained in a block – surrounded by {}

Here is a basic java program.  See if you can run it.  Note the use of escape characters when printing.  Notice that \n gives a new line and \" literally prints "

public class JavaApplication1 {

    public static void main(String[] args) {
       System.out.println("This is really \n... \"groovy!\"");
    }
}

Be careful typing a backslash in Java. It indicates that the next character will be a special code. Be especially careful when writing file paths if you’re a Windows user. Follow the Apple/Linux pattern and use forward slashes, e.g. “C:/Java/Spoons”

Escape SequenceCharacter
\nnewline
\ttab
\bbackspace
\fform feed
\nreturn
\”” (double quote)
\’‘ (single quote)
\\\ (back slash)
\uDDDDUnicode character (DDDD is four hex digits)

Here’s how you read in text. Notice the import scanner line at the beginning.

import java.util.Scanner;

public class JavaApplication1 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter your name");
        String s = scan.nextLine();
        System.out.println("Hello " + s);
    }

Questions

  1. Print the message “I \u2665 Java!”
  2. Look up the the unicode for pi, and use that to print the formula for the circumference of a circle, C=2πr.
  3. Prompt the user to input their name and age. Output a message of the form “Hello (name). You are (age) years old.”
  4. Prompt the user to input first their forename and then their surname. Output their name in the format surname, forename.
  5. Use tabs to print out the following table. (Don’t include the borders)
JohnSmith32
JillGreen35
JackBlack22