# 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”))

## 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.

# 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));```

# 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.

# 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”

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);
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)

## Code is Poetry

Brian Bilston has written a History of Modern Art in Poetry.  I  wondered what it would be like to do something similar in various programming languages.

Here’s the original poem:

Roses are red
Violets are blue
Sugar is sweet
And so are you

Here’s the poem constructed using a zip statement in Haskell

```Prelude> zip ["roses","violets","sugar","you"]["red","blue","sweet","sweet"]
[("roses","red"),("violets","blue"),("sugar","sweet"),("you","sweet")]```

The list produced holds the relationship that sugar is sweet and you are sweet. The comparison between “you” and sugar is not made clear.

### Lisp

Here’s the poem stored as an alist in Lisp

```(setq poem '(("roses" . "red") ("violets" . "blue") ("sugar" . "sweet")("you" . "sweet")))
(mapcar (lambda (x) (concat (car x) " are " (cdr x))) poem)```

I’ve gone one stage further here, using a mapcar function to produce something that looks a little bit more like the original poem, however we’re still missing the connection between “you” and sugar.

`("roses are red" "violets are blue" "sugar are sweet" "you are sweet")`

### Python

Of course, sugar are sweet isn’t right.   Let’s try some Python.

```poem = {"roses":"red","violets":"blue","sugar":"sweet","you":"sweet"}

for key, value in poem.items():
if key == "sugar":
print(key, "is" ,value)
else:
print(key, "are", value)
```

This output is at least grammatically correct.

```roses are red
violets are blue
sugar is sweet
you are sweet
```

### Java

Java can do something similar using a HashMap

```Map<String, String> poem = new HashMap<String, String>();

poem.put("roses", "red");
poem.put("violets", "blue");
poem.put("sugar", "sweet");
poem.put("you", "sweet");

for (Map.Entry<String, String> entry : poem.entrySet()) {
if(entry.getKey().equals("sugar")){
System.out.println(entry.getKey() + " is " + entry.getValue());
} else{
System.out.println(entry.getKey() + " are " + entry.getValue());
}

}
```

But we’re still no closer to conveying the connection between “you” being sweet, just like sugar is sweet.

Fortunately, Java allows us to use some object oriented design to better convey the meaning of the poem.

In the example below I’ve used an interface to allow sweetness to be applied to both sugar and to the special one to whom the poem refers.  The comparison is at last made clear.  As there can only be one true love, it seemed reasonable to make a singleton class for TheOne, inherited from a regular person.

Run the code and the poem is printed out properly, just like the original.  More importantly though, the concepts to which the poem refers are properly encapsulated and related.

The original poem was only 4 lines long.  My implementation takes 80 lines, but I think you’ll agree I’ve done a rather better job, providing clarity and removing any ambiguity.

```public class Love {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Flower [] rose = new Flower; // 12 roses in a bunch
Flower [] violet = new Flower; // more violets in bunch
Sugar sugar = new Sugar();
TheOne myLove = TheOne.getInstance();  // Singleton class
// There can only be one true love

rose = new Flower();
rose.setColour("red");  // colour is static so only need
// to instantiate one here

violet = new Flower();
violet.setColour("blue");

System.out.println("Roses are " + rose.getColour());
System.out.println("Violets are " + violet.getColour());
System.out.println(sugar.sweet());
System.out.println(myLove.sweet());
}

}

class Flower {
private static String colour;

public void setColour(String colour){
this.colour = colour;
}

public String getColour (){
return colour;
}
}

class Sugar implements Sweetness {

@Override
public String sweet() {
return "Sugar is sweet";
}

}

class Person {
public String sweet()
{
return "Not sweet";
}
}

class TheOne extends Person implements Sweetness{
private static TheOne instance = null;

private TheOne()
{

}

public static TheOne getInstance()
{
if(instance == null)
instance = new TheOne();

return instance;
}

@Override
public String sweet() {
return "And so are you";
}
}

interface Sweetness {
String sweet();
}
```

## JDBC 8: The Complete Code

```package dbase2016;

/**
*
* @author ajb
*/
public class DBase2016 {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
}

}
```
```package dbase2016;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

/**
*
* @author ajb
*/
public class DBase {

private static Connection con;

DBase() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {
System.err.println(ex);
}

}

public static void makeConnection() {
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bluecoat", "root", "");
} catch (SQLException ex) {
System.err.println(ex);
}

}

public static void printPupils() {

Statement statement;
makeConnection();
try {
statement = con.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM Student");

while (rs.next()) {
System.out.println("Forename: " + rs.getString("Forename")
+ " Surname: " + rs.getString("Surname")
+ " Gender: " + rs.getString("Gender")
+ " Form: " + rs.getString("Form"));
}

con.close();

} catch (SQLException ex) {
System.err.println(ex);
}
}

public static ArrayList<Student> getPupils()
{
ArrayList<Student> students = new ArrayList();
Statement statement;
makeConnection();
try {
statement = con.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM Student");

while (rs.next()) {

Student student = new Student();
student.setForename(rs.getString("Forename"));
student.setSurname(rs.getString("Surname"));
student.setGender(rs.getString("Gender"));
student.setForm(rs.getString("Form"));
}

con.close();

} catch (SQLException ex) {
System.err.println(ex);
}

return students;
}

makeConnection();
try {
PreparedStatement prep = con.prepareStatement("INSERT INTO Student (Forename, Surname, Gender, Form) VALUES (?,?,?,?)");
prep.setString(1, "Last");
prep.setString(2, "James");
prep.setString(3, "M");
prep.setString(4, "9C");

prep.executeUpdate();

con.close();

} catch (SQLException ex) {
System.err.println(ex);
}

}

public static void addStudent(Student student) {

makeConnection();
try {
PreparedStatement prep = con.prepareStatement("INSERT INTO Student (Forename, Surname, Gender, Form) VALUES (?,?,?,?)");
prep.setString(1, student.getForename());
prep.setString(2, student.getSurname());
prep.setString(3, student.getGender());
prep.setString(4, student.getForm());

prep.executeUpdate();

con.close();

} catch (SQLException ex) {
System.err.println(ex);
}

}

}
```
```package dbase2016;

/**
*
* @author ajb
*/
public class Student {
private String forename;
private String surname;
private String gender;
private String form;

/**
* @return the forename
*/
public String getForename() {
return forename;
}

/**
* @param forename the forename to set
*/
public void setForename(String forename) {
this.forename = forename;
}

/**
* @return the surname
*/
public String getSurname() {
return surname;
}

/**
* @param surname the surname to set
*/
public void setSurname(String surname) {
this.surname = surname;
}

/**
* @return the gender
*/
public String getGender() {
return gender;
}

/**
* @param gender the gender to set
*/
public void setGender(String gender) {
this.gender = gender;
}

/**
* @return the form
*/
public String getForm() {
return form;
}

/**
* @param form the form to set
*/
public void setForm(String form) {
this.form = form;
}

}
```
```package dbase2016;

import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
*
* @author ajb
*/
public class GUIDisplayStudents extends JFrame {

JTextArea textArea;
JScrollPane scrollPane;

GUIDisplayStudents()
{
this.setSize(300,200);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textArea = new JTextArea("Sample Text");
scrollPane = new JScrollPane(textArea);

}

GUIDisplayStudents(ArrayList<Student> students)
{
this.setSize(300,200);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textArea = new JTextArea();
scrollPane = new JScrollPane(textArea);
for(Student student : students)
{
textArea.append(student.getForename() + " " + student.getSurname() + "\n");
}

}

}
```
```package dbase2016;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

/**
*
* @author ajb
*/
public class GUIAddStudent extends JFrame implements ActionListener{

JLabel lblForename = new JLabel("Forename");
JLabel lblSurname = new JLabel("Surname");
JLabel lblGender = new JLabel("Gender");
JLabel lblForm = new JLabel("Form");

JTextField txtForename = new JTextField("");
JTextField txtSurname = new JTextField("");
JTextField txtGender = new JTextField("");
JTextField txtForm = new JTextField("");

JButton OK = new JButton("OK");

{
Container vert = Box.createVerticalBox();

this.setSize(300,250);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

@Override
public void actionPerformed(ActionEvent ae) {
Student student = new Student();
student.setForename(txtForename.getText());
student.setSurname(txtSurname.getText());
student.setGender(txtGender.getText());
student.setForm(txtForm.getText());

GUIDisplayStudents  displayPupils = new GUIDisplayStudents(DBase.getPupils());
displayPupils.setVisible(true);
}

}
```

## JDBC 7: Adding Students using a GUI

`public static void addStudent(Student student) {   makeConnection();    try {    PreparedStatement prep = con.prepareStatement("INSERT INTO Student (Forename, Surname, Gender, Form) VALUES (?,?,?,?)");    prep.setString(1, student.getForename());    prep.setString(2, student.getSurname());    prep.setString(3, student.getGender());    prep.setString(4, student.getForm());    prep.executeUpdate();    con.close();   } catch (SQLException ex) {     System.err.println(ex);       }}`

The following code will display the simple GUI shown `package dbase2016;import java.awt.Container;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.Box;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JTextField;/** * * @author ajb */public class GUIAddStudent extends JFrame implements ActionListener{    JLabel lblForename = new JLabel("Forename");        JLabel lblSurname = new JLabel("Surname");    JLabel lblGender = new JLabel("Gender");    JLabel lblForm = new JLabel("Form");    JTextField txtForename = new JTextField("");    JTextField txtSurname = new JTextField("");    JTextField txtGender = new JTextField("");    JTextField txtForm = new JTextField("");    JButton OK = new JButton("OK");    GUIAddStudent()    {       Container vert = Box.createVerticalBox();       vert.add(lblForename);       vert.add(txtForename);       vert.add(lblSurname);       vert.add(txtSurname);       vert.add(lblGender);       vert.add(txtGender);       vert.add(lblForm);       vert.add(txtForm);       vert.add(OK);       OK.addActionListener(this);       add(vert);       this.setSize(300,250);       this.setLocationRelativeTo(null);       this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     }    @Override    public void actionPerformed(ActionEvent ae) {       Student student = new Student();       student.setForename(txtForename.getText());       student.setSurname(txtSurname.getText());       student.setGender(txtGender.getText());       student.setForm(txtForm.getText());       DBase.addStudent(student);       GUIDisplayStudents  displayPupils = new GUIDisplayStudents(DBase.getPupils());       displayPupils.setVisible(true);    }}`

## Create a DBase.getPupils() method

A method to fetch all the pupils. They are wrapped in the Student class and then returned as an ArrayList

```public static ArrayList<Student> getPupils()
{
ArrayList<Student> students = new ArrayList();
Statement statement;
makeConnection();
try {
statement = con.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM Student");

while (rs.next()) {

Student student = new Student();
student.setForename(rs.getString("Forename"));
student.setSurname(rs.getString("Surname"));
student.setGender(rs.getString("Gender"));
student.setForm(rs.getString("Form"));
}

con.close();

} catch (SQLException ex) {
System.err.println(ex);
}

return students;
}```

## Use the getPupils() method in the GUI

```package dbase2016;

import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
*
* @author ajb
*/
public class GUIDisplayStudents extends JFrame {

JTextArea textArea;
JScrollPane scrollPane;

GUIDisplayStudents(ArrayList<Student> students)
{
this.setSize(300,200);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textArea = new JTextArea();
scrollPane = new JScrollPane(textArea);
for(Student student : students)
{
textArea.append(student.getForename() + " " + student.getSurname() + "\n");
}

}

}
```
```package dbase2016;

/**
*
* @author ajb
*/
public class DBase2016 {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
GUIDisplayStudents  displayPupils = new GUIDisplayStudents(DBase.getPupils());
displayPupils.setVisible(true);
}

}```

## JDBC 5: Creating a GUI

A simple GUI to display database contents

```package dbase2016;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
*
* @author ajb
*/
public class GUIDisplayStudents extends JFrame {

JTextArea textArea;
JScrollPane scrollPane;

GUIDisplayStudents()
{
this.setSize(300,200);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textArea = new JTextArea("Sample Text");
scrollPane = new JScrollPane(textArea);

}

}```

## Student Class

This will be used to wrap the data retrieved from the database

```package dbase2016;

/**
*
* @author ajb
*/
public class Student {
private String forename;
private String surname;
private String gender;
private String form;

/**
* @return the forename
*/
public String getForename() {
return forename;
}

/**
* @param forename the forename to set
*/
public void setForename(String forename) {
this.forename = forename;
}

/**
* @return the surname
*/
public String getSurname() {
return surname;
}

/**
* @param surname the surname to set
*/
public void setSurname(String surname) {
this.surname = surname;
}

/**
* @return the gender
*/
public String getGender() {
return gender;
}

/**
* @param gender the gender to set
*/
public void setGender(String gender) {
this.gender = gender;
}

/**
* @return the form
*/
public String getForm() {
return form;
}

/**
* @param form the form to set
*/
public void setForm(String form) {
this.form = form;
}

}```

# The Code so Far

```package dbase2016;

/**
*
* @author ajb
*/
public class DBase2016 {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
DBase.printPupils();
}

}
```
```package dbase2016;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
*
* @author ajb
*/
public class DBase {

private static Connection con;

DBase() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {
System.err.println(ex);
}

}

public static void makeConnection() {
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bluecoat", "root", "");
} catch (SQLException ex) {
System.err.println(ex);
}

}

public static void printPupils() {

Statement statement;
makeConnection();
try {
statement = con.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM Student");

while (rs.next()) {
System.out.println("Forename: " + rs.getString("Forename")
+ " Surname: " + rs.getString("Surname")
+ " Gender: " + rs.getString("Gender")
+ " Form: " + rs.getString("Form"));
}

con.close();

} catch (SQLException ex) {
System.err.println(ex);
}
}

makeConnection();
try {
PreparedStatement prep = con.prepareStatement("INSERT INTO Student (Forename, Surname, Gender, Form) VALUES (?,?,?,?)");
prep.setString(1, "Last");
prep.setString(2, "James");
prep.setString(3, "M");
prep.setString(4, "9C");

prep.executeUpdate();

con.close();

} catch (SQLException ex) {
System.err.println(ex);
}

}

}```