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.

Test data

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) {
    GUIAddStudent  addStudent = new GUIAddStudent();
    addStudent.setVisible(true);
    }

}
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"));
        students.add(student);
        }

        con.close();

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

    return students;
    }

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

    }

    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);
    add(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");
    }
    add(scrollPane);

    }

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

JDBC 7: Adding Students using a GUI

Create DBase.addStudent(Student student) Method

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

Create GUIAddStudent Class

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

JDBC 6: Get Pupils and Display in GUI

Create a DBase.getPupils() method

Update: Follow this link to watch a YouTube demonstration of the following

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"));
        students.add(student);
        }

        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");
    }
    add(scrollPane);

    }

}
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

Update: Follow this link to watch a YouTube demonstration of the following

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);
    add(scrollPane);

    }

}

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

}

JDBC 4: The Code so Far…

The Code so Far

package dbase2016;

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

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
    DBase.addStudent();
    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);
    }
    }

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

    }

}

JDBC 3: Queries

Fetch ResultSet

Update: Follow this link to watch a YouTube demonstration of the following

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.addStudent();
    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.

Update: Follow this link to watch a YouTube demonstration of this lesson

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

}

– More Collections: Return to Lisp Problems Solutions

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));
14:      encoded.add(pair);
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:     {
 9:         decoded.add(pair.value);
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:     {
 7:     dup.add(s);
 8:     dup.add(s);
 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:     {
 9:         rep.add(s);
10:     }
11:     }
12: 
13:     return rep;
14: }

7: More Collections: Return to Lisp Problems

These problems were inspired by the 99 Lisp problems. Lisp is a very different language to Java; its use of lists means it’s not appropriate to emulate all the original problems in Java, however, there is some benefit in practising the use of Java collections.

The introduction of lambda functions in Java8 made me rethink how best to approach these problems. There are three things being practised here: collections, generics and lambdas. I’ve split up the questions so that they give a chance to practice these different skills.

1 Last Item

Find the last item in an List of String objects

1.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "fork", "spoon"));
2: System.out.println(lastItem(myList));
3:  *** Output ***
4: spoon

2 Last Item Generic

Find the last item in a Generic List

2.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "fork", "spoon"));
2: List<Integer> anotherList = new ArrayList<>(asList(1,2,3));
3: System.out.println(gLastItem(myList));
4: System.out.println(gLastItem(anotherList));
5:  *** Output ***
6: spoon
7: 3

3 Last But One

Find the last but one item in a List

3.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "fork", "spoon"));
2: System.out.println(lastButOneItem(myList));
3:  *** Output ***
4: fork

4 Iterate through the Elements of a List

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

4.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "fork", "spoon"));
2: System.out.println(printEach(myList));
3:  *** Output ***
4: knife
5: fork
6: spoon

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 Example

1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
2: printEach(removeDuplicates(myList));
3:  *** Output ***
4: knife
5: fork
6: spoon

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 Example

1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
2: printEach(removeDuplicates(myList));
3:  *** Output ***
4: knife
5: fork
6: spoon

Remembering that a HashSet cannot contain duplicates

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.

Use this Pair class

 1: class Pair<T>
 2:    {
 3:        int count;
 4:        T value;
 5: 
 6:        Pair(int count, T value) 
 7:        {
 8:        this.count = count;
 9:        this.value = value;
10:        }
11: 
12:        void print()
13:        {
14:        System.out.print("("+ count + ", " + value +") ");
15:        }
16:    } 

7.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
2:  List<Pair> rle = RLE(myList);
3:  for (Pair r: rle)
4:  {
5:      r.print();
6:  }
7:  System.out.println("");
8:  *** Output ***
9: (2, knife) (1, fork) (2, spoon)

8 Decode a run-length encoded list

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

8.1 Example

 1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
 2:     List<Pair> rle = RLE(myList);
 3:     for (Pair r: rle)
 4:     {
 5:         r.print();
 6:     }
 7:     System.out.println("");
 8: 
 9:     List<Object> decoded = decodeRLE(rle);
10: 
11:     for (Object o: decoded)
12:     {
13:         System.out.println(o);
14:     }
15:  *** Output ***
16: (2, knife) (1, fork) (2, spoon) 
17: knife
18: knife
19: fork
20: spoon
21: spoon

9 Duplicate the elements of a list

9.1 Example

 1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
 2: printEach(dupli(myList));
 3:  *** Output ***
 4: knife
 5: knife
 6: knife
 7: knife
 8: fork
 9: fork
10: spoon
11: spoon
12: spoon
13: spoon

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

10.1 Example

 1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
 2: printEach(repli(myList,3));
 3:  *** Output ***
 4: knife
 5: knife
 6: knife
 7: knife
 8: knife
 9: knife
10: fork
11: fork
12: fork
13: spoon
14: spoon
15: spoon
16: spoon
17: spoon
18: spoon