## Question Loop Examples

### A Basic Question Loop

```answer = ""

answer = input("What is the capital of Paris?")

print("Correct!")
```

### A Question Loop with a Count

Keep a count of how many attempts were made

```answer = ""
count = 0

answer = input("What is the capital of Paris?")
count = count + 1

print("Correct!")
print("You took ", count , "goes")
```

### A Question Loop with a Flag

```finished = False
number = 0
print("Denary to Binary Converter")
print("Enter -1 to finish")

while (finished == False):
number = int(input("Enter a number in Denary"))
if (number == -1):
finished = True
else:
print("{:b}".format(number))
```

### A Question Loop with a Count and a Flag

```finished = False
correct = False
tries = 3

while (finished == False):
finished = True
correct = True
elif (tries == 1):
finished = True
correct = False
else:
tries = tries - 1
print("Wrong.  You have", tries, "tries remaining")

if(correct == True):
print("You're in!")
else:
print("Locked out!")
```

## Exercise

1. Write a program that asks “Are we there yet?” and prompts the user to enter an answer. The program loops until the user enters “Yes”. The program then outputs “Hooray!”
2. Write a program that asks the user to guess a number between 1 and 10. The program loops until the user enters the correct answer . The program then outputs then the number of guesses made.
3. Modify the program from question 2 so that the user now has to guess a number between 1 and 100. The program outputs “Too low” if the guess is lower the number, “Too high” if the guess is highter than the number and “Correct” if the guess is correct. The program then terminates
4. The following code converts pounds to kilograms. Write a program that prompts the user to enter a weight in pounds or -1 to terminate. The program will output the weight in kilograms. If -1 is entered the program will print “Goodbye”
```pounds = 4
kilograms = pounds * 0.453592
print(kilograms)
```
1. A house alarm system is triggered when the front door is open. The user has three attempts to enter a four digit code. If the user enters the correct code the system outputs “Deactivated!”. If the user enters the incorrect code the system outputs the number of attempts remaining. If the user does not enter the correct code within three attempts the system outputs “Alarm!”

Write a program to simulate the above.

### Extension

Write a quiz program that asks the user 5 questions. The user is allowed 2 attempts at each question. At the end the program prints out the users score out of 5

## Data Types: int and float (Level 3)

Remember that the input command reads strings. You have to convert strings to integers (whole numbers) or floats (decimals) if you want to use them to perform calculations.

## Examples

1) Write a program that prompts the user to enter the length and width of a rectangle. Output the area of the rectangle

```length = int(input("Enter the length of the rectangle"))
width = int(input("Enter the width of the rectangle"))
area = length*width
print("The rectangle has an area of " + str(area))
```

2) To convert miles to kilometers, you multiply the number of miles by 1.609. Write a program that prompts the user to enter the number of miles, and then output the answer converted to kilometers

Note the use of float as a user may input 12.5 miles, for example.

```miles = float(input("Enter the number of miles"))
kilometers = miles * 1.609
print(str(miles) + " miles = " + str(kilometers) + " kilometers")
```

## Exercise

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 (Don’t forget to convert the input to a float!)
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

## Extension: 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. Now write a program to convert Celsius to Fahrenheit. Use the test data to check your program.
2. Write a program to convert Fahrenheit to Celsius. Again, use the test data below to check your program.

C F
0 32
12 54
100 212
-3 27
-18 0
-23 -10

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

}

}```

## Fetch ResultSet

Once you have a connection, you can now fetch data from the database. Add the following method to the DBase class.

• The method creates a statement attached to the connection con.
• The statement executes a simple MySQL query. The query results are stored in a ResultSet rs.
• A pointer is set to before the first record in the ResultSet.
• A while statement is used to traverse the set.
• Finally, the connection is closed.
```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);
}
}
```
```package dbase2016;

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

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

DBase.printPupils();
}

}```

## Add a record using a PreparedStatement

Note that we use executeQuery() to retrieve data and executeUpdate() to update the database.  Here we’ve hard coded the student we’re adding.   A later section will show how to add any student.

```public static void addStudent() {

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

}
```
```package dbase2016;

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

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

}```

## JDBC 2: Database Class

The following is the class I’m going to use for the main part of this tutorial. It’s just the Quick Start code broken down into methods.

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

}

}
```

Check the connection by calling the makeConnection() method as follows. If everything is okay the program will simply terminate. If an exception is thrown, check your port number, username and password.

```package dbase2016;

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

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

}```

## 1 Last Item

Find the last item in an List of String objects

### 1.1 Solution

```1: String lastItem(List<String> a)
2: {
3:     return  a.get(a.size()-1);
4: }
```

## 2 Last Item Generic

Find the last item in a Generic List

### 2.1 Solution

```1: Object gLastItem(List<?> a)
2: {
3:     return  a.get(a.size()-1);
4: }
```

## 3 Last But One

Find the last but one item in a List

### 3.1 Solution

```1: Object lastButOneItem(List<?> a)
2: {
3:     if (a.size() > 1)
4:  return  a.get(a.size()-2);
5:     else
6:  return "List too small";
7: }
```

## 4 Iterate through the Elements of a List

Iterate through the Elements of a List, printing them out in turn

### 4.1 Solution

```1: void printEach(List<?> a)
2: {
3:     for (Object e: a)
4:     {
5:  System.out.println(e);
6:     }
7: }
```

or using a stream

```1: void streamPrintEach(List<?> list)
2: {
3:     list
4:  .stream()
5:  .forEach(System.out::println);
6:
7: }
```

## 5 Eliminate consecutive duplicates from a List.

Write a method that removes consecutive duplicates from a List. The order of the elements should not be changed.

### 5.1 Solution

```1: List<?> removeDuplicates(List<?> a)
2: {
3:     for (int i = 0; i<a.size()-1; i++)
4:     {
5:  if(a.get(i) == a.get(i+1)) a.remove(a.get(i));
6:     }
7:     return a;
8: }
```

## 6 Eliminate consecutive duplicates from a List using HashSet

Remembering that a HashSet cannot contain duplicates, repeat the above question using a HashSet

### 6.1 Solution

```1: HashSet<String> hashRemoveDuplicates(List<String> a)
2: {
3:     HashSet<String> hSet = new HashSet<String>(a);
4:     return hSet;
5: }
```

## 7 RLE

Run-length encoding of a list. Consecutive duplicates of elements are encoded as pairs where N is the number of duplicates of the element E.

Note this solution uses the Pair class, defined in the question

### 7.1 Solution

``` 1: List<Pair> RLE(List<?> list)
2: {
3:     List<Pair> encoded = new ArrayList<Pair>();
4:     for (int i = 0; i < list.size(); i++)
5:     {
6:     int runLength = 1;
7:     while (i < list.size() -1 && list.get(i) == list.get(i+1))
8:     {
9:         runLength++;
10:         i++;
11:     }
12:
13:      Pair<Object> pair = new Pair<Object>(runLength, list.get(i));
15:     }
16:     return encoded;
17:
18: }
```

## 8 Decode a run-length encoded list

Given a run-length code list generated in a previous problem, construct its uncompressed version.

Note this solution uses the Pair class, defined in the question

### 8.1 Solution

``` 1: List<Object> decodeRLE(List<Pair> list)
2: {
3:
4:     List<Object> decoded = new ArrayList<Object>();
5:     for (Pair pair: list)
6:     {
7:     for (int i =0; i<(int)pair.count; i++)
8:     {
10:     }
11:     }
12:
13:     return decoded;
14: }
```

## 9 Duplicate the elements of a list

### 9.1 Solution

``` 1: List<String> dupli(List<String> list)
2: {
3:     List<String> dup = new ArrayList<String>();
4:
5:     for(String s: list)
6:     {
9:     }
10:
11:     return dup;
12: }
```

or, using a stream

```1: List<String> streamDupli(List<String> list)
2: {
3:     List<String> dupli = list
4:              .stream()
5:              .collect(Collectors.toList());
6:
7:     return dupli;
8:
9: }
```

## 10 Replicate the elements of a list a given number of times

### 10.1 Solution

``` 1: List<String> repli(List<String> list, int num)
2: {
3:     List<String> rep = new ArrayList<String>();
4:
5:     for(String s: list)
6:     {
7:     for (int i=0; i<num; i++)
8:     {