import java.util.ArrayList;
/**
This class computes the average of a set of data values.
*/
public class DataSet
{
/**
Constructs an empty data set.
*/
public DataSet()
{
create ArrayList
/* write your code here */
}
/**
Adds a data value to the data set
@param x a data value
*/
public void add(double x)
{
/* write your code here */
}
/**
Gets the average of the added data.
@return the average or 0 if no data has been added
*/
public double getAverage()
{
/* write your code here */
}
private ArrayList data;
}
ArrayLists with Generic Types
The type ArraList identifies an array list of bank accounts.
The angle brackets around the BankAccount type tell you that BankAccount is a type parameter.
Use an ArrayList whenever you want to collect objects of type T.
However, you cannot use primitive types as type parameters — there is no ArrayList or ArrayList.
Wrapper objects can be used anywhere that objects are required instead of primitive type values. For example, you can collect a sequence of floating-point numbers in an ArrayList.
Conversion between primitive types and the corresponding wrapper classes is automatic. This process is called auto-boxing (even though auto-wrapping would have been more consistent).
For example, if you assign a number to a Double object, the number is automatically “put into a box”, namely a wrapper object.
Double d = 29.95; // auto-boxing; same as Double d = new Double(29.95);
Wrapper objects are automatically “unboxed” to primitive types.
double x = d; // auto-unboxing; same as double x = d.doubleValue();
ArrayList data = new ArrayList();
data.add(29.95);
double x = data.get(0);
Classwork:
1. Change DestinysChild and Recipe classes to use parameter types.
2. Create a class DataSet of BankAccounts. The constructor creates an ArrayList. Write the test class to add, delete and print bank accounts.
3. Create a class Purse that contains an ArrayList of Coin(s). Write the test class to add, delete, and print coins.
The ArrayList class is part of the java.util package of the Java standard class library.
It provides a service similar to an array in that it can store a list of values and reference them by an index. However, whereas an array remains a fixed size throughout its existence, an ArrayList object dynamically grows and shrinks as needed.
A data element can be inserted into or removed from any location (index) of an ArrayList object with a single method invocation.
The ArrayList class is part of the Collections API, a group of classes that serve to organize and manage other objects.
Unlike an array, an ArrayList is not declared to store a particular type.
An ArrayList object stores a list of references to the Object class.
A reference to any type of object can be added to an ArrayList object.
Because an ArrayList stores references, a primitive value must be stored in an appropriate wrapper class in order to be stored in an ArrayList. Figure 6.8 lists several methods of the ArrayList class.
/**
A coin with a monetary value.
*/
public class Coin
{
/**
Constructs a coin.
@param aValue the monetary value of the coin.
@param aName the name of the coin
*/
public Coin(double aValue, String aName)
{
value = aValue;
name = aName;
}
/**
Gets the coin value.
@return the value
*/
public double getValue()
{
return value;
}
/**
Gets the coin name.
@return the name
*/
public String getName()
{
return name;
}
public boolean equals(Object otherObject)
{
Coin other = (Coin)otherObject;
return name.equals(other.name)
(and) value == other.value;
}
private double value;
private String name;
}
import java.util.ArrayList;
/**
A purse holds a collection of coins.
*/
public class Purse
{
/**
Constructs an empty purse.
*/
public Purse()
{
coins = new ArrayList();
}
/**
Add a coin to the purse.
@param aCoin the coin to add
*/
public void add(Coin aCoin)
{
coins.add(aCoin);
}
/**
Get the total value of the coins in the purse.
@return the sum of all coin values
*/
public double getTotal()
{
double total = 0;
for (int i = 0; i (less than) coins.size(); i++)
{
Coin aCoin = (Coin)coins.get(i);
total = total + aCoin.getValue();
}
return total;
}
private ArrayList coins;
}
How long does a linear search take? If we assume that the element v is present in the array a, then the average search visits n/2 elements, where n is the length of the array. If it is not present, then all n elements must be inspected to verify the absence. Either way, a linear search is an O(n) algorithm.
A binary search is an O(log(n)) algorithm.
That result makes intuitive sense. Suppose that n is 100. Then after each search,
the size of the search range is cut in half, to 50, 25, 12, 6, 3, and 1. After seven comparisons we are done. This agrees with our formula, because log2(100) ≈ 6.64386, and indeed the next larger power of 2 is 27 = 128.
Selection Sort: Let us count the number of operations that the program must carry out to sort an array with the selection sort algorithm. We don’t actually know how many machine operations are generated for each Java instruction, or which of those instructions are more time consuming than others, but we can make a simplification. We will simply count how often an array element is visited. Each visit requires about the same amount of work by other operations, such as incrementing subscripts and comparing values.
Let n be the size of the array. First, we must find the smallest of n numbers. To achieve that, we must visit n array elements. Then we swap the elements, which takes two visits. (You may argue that there is a certain probability that we don’t need to swap the values. That is true, and one can refine the computation to reflect that observation. As we will soon see, doing so would not affect the overall conclusion.) In the next step, we need to visit only n − 1 elements to find the minimum. In the following step, n − 2 elements are visited to find the minimum. The last step visits two elements to find the minimum. Each step requires two visits to swap the elements. Therefore, the total number of visits is
n + 2 + (n − 1) + 2 + … + 2 + 2 =
n + (n − 1) + … + 2 + (n − 1) ⋅ 2 =
2 + … + (n-1) + n + (n – 1) ⋅ 2 =
n (n – 1)
——— – 1 + (n – 1) ⋅ 2
2
multiplying out and collecting terms of n:
1 5
— n2 + — n – 3
2 2
Let’s simplify the analysis further:
When you plug in a large value for n (say 1,000 or 2,000)
1
— n2 is 500,000 or 2,000,000
2
5
— n – 3 is only 2,497 or 4,997. Neither of these two number would have an impact on
2
the magnitude of 500,000 and 2,000,000. We can just ignore them for the purpose of the analysis.
Further more, we will show that 1/2 in the square term does not have much of an effect in our analysis
We are not interested in the actual count of visits for a single n. We want to compare the ratios of counts for different values of n.
If we want to compare the number of visits required to sort an array of 1,000 elements to an array of 2,000, by what factor the number of visits would increase?
The factor of 1/2 cancels out in comparison of this kind. We will simply say, “The number of visits is of order n2“. That way, we can easily see that the number of comparisons increases fourfold when the size of the array doubles: (2n)2 = 4n2.
To indicate that the number of visits is of the order n2, we will use the big-Oh notation: O(n2)
The big-Oh notation is about the fastest-growing term, n2, and ignores its constant coefficient, no matter how large or small it may be.
It is safe to say that the number of machine operations, and the actual amount of time that the computer spends on them, is approximately proportional to the number of element visits. For argument sake, we could say that there are about 10 machine operations for every element visit. Then, then number of machine operations should be in the neighborhood of 10 x (1/2) n2. Using the big-Oh notation, we can say that the number of machine operations required to sort is in the order of n2 or O(n2) and so is the sorting time.
If an array is increase by a factor of 100, the sorting time increases by a factor of 10,000. To sort an array of a million elements, takes 10,000 times as long as sorting an array of 10,000 items.If 10,000 items can be sort in about half a second, then sorting one million items requires well over an hour.
1. If you increase the size of a data set tenfold, how much longer does it take to sort it with the selection sort algorithm?
2. How large does n need to be so that (1/2)n2 is bigger than (5/2)n – 3?
//********************************************************************
// Searches.java Author: Lewis/Loftus/Cocking
//
// Demonstrates the linear and binary search algorithms.
//********************************************************************
public class Searches
{
//-----------------------------------------------------------------
// Searches the array of integers for the specified element using
// a linear search. The index where the element was found is
// returned, or -1 if the element is not found.
//-----------------------------------------------------------------
public static int linearSearch (int[] numbers, int key)
{
for (int index = 0; index < numbers.length; index++)
if (key == numbers[index])
return index;
return -1;
}
//-----------------------------------------------------------------
// Searches the array of integers for the specified element using
// a binary search. The index where the element was found is
// returned, or -1 if the element is not found.
// NOTE: The array must be sorted!
//-----------------------------------------------------------------
public static int binarySearch (int[] numbers, int key)
{
int low = 0, high = numbers.length-1, middle = (low + high) / 2;
while (numbers[middle] != key && low <= high)
{
if (key < numbers[middle])
high = middle - 1;
else
low = middle + 1;
middle = (low + high) / 2;
}
if (numbers[middle] == key)
return middle;
else
return -1;
}
}
Classwork: Work on this two assignments
Given the following list of numbers, how many elements of the list would be examined by the linear search algorithm to determine if each of the indicated target elements are on the list? Trace the steps on paper.
15 21 4 17 8 27 1 22 43 57 25 7 53 12 16
a. 17
b. 15
c. 16
d. 45
Describe the general concept of a binary search. Tell the story and be creative.
Given the following list of numbers, how many elements of the list would be examined by the binary search algorithm to determine if each of the indicated target elements are on the list? Trace the steps on paper and hand it in.
1 4 7 8 12 15 16 17 21 22 25 27 43 53 57
a. 17
b. 15
c. 57
d. 45
Assignments:
Self-Review 6.9 and 6.10
MC 6.5
T/F 6.7
The ArrayList class is a generic class: ArrayList collects objects of type T.
/**
A bank account has a balance that can be changed by
deposits and withdrawals.
*/
public class BankAccount
{
/**
Constructs a bank account with a zero balance
@param anAccountNumber the account number for this account
*/
public BankAccount(int anAccountNumber)
{
accountNumber = anAccountNumber;
balance = 0;
}
/**
Constructs a bank account with a given balance
@param anAccountNumber the account number for this account
@param initialBalance the initial balance
*/
public BankAccount(int anAccountNumber, double initialBalance)
{
accountNumber = anAccountNumber;
balance = initialBalance;
}
/**
Gets the account number of this bank account.
@return the account number
*/
public int getAccountNumber()
{
return accountNumber;
}
/**
Deposits money into the bank account.
@param amount the amount to deposit
*/
public void deposit(double amount)
{
double newBalance = balance + amount;
balance = newBalance;
}
/**
Withdraws money from the bank account.
@param amount the amount to withdraw
*/
public void withdraw(double amount)
{
double newBalance = balance - amount;
balance = newBalance;
}
/**
Gets the current balance of the bank account.
@return the current balance
*/
public double getBalance()
{
return balance;
}
private int accountNumber;
private double balance;
}
A driver class:
import java.util.ArrayList;
/**
This program tests the ArrayList class.
*/
public class ArrayListTester
{
public static void main(String[] args)
{
ArrayList accounts
= new ArrayList();
accounts.add(new BankAccount(1001));
accounts.add(new BankAccount(1015));
accounts.add(new BankAccount(1729));
accounts.add(1, new BankAccount(1008));
accounts.remove(0);
System.out.println("Size: " + accounts.size());
System.out.println("Expected: 3");
BankAccount first = accounts.get(0);
System.out.println("First account number: "
+ first.getAccountNumber());
System.out.println("Expected: 1015");
BankAccount last = accounts.get(accounts.size() - 1);
System.out.println("Last account number: "
+ last.getAccountNumber());
System.out.println("Expected: 1729");
}
}
A different implementation:
Note: pay attention to the for-each loops
import java.util.ArrayList;
/**
This bank contains a collection of bank accounts.
*/
public class Bank
{
/**
Constructs a bank with no bank accounts.
*/
public Bank()
{
accounts = new ArrayList();
}
/**
Adds an account to this bank.
@param a the account to add
*/
public void addAccount(BankAccount a)
{
accounts.add(a);
}
/**
Gets the sum of the balances of all accounts in this bank.
@return the sum of the balances
*/
public double getTotalBalance()
{
double total = 0;
for (BankAccount a : accounts)
{
total = total + a.getBalance();
}
return total;
}
/**
Counts the number of bank accounts whose balance is at
least a given value.
@param atLeast the balance required to count an account
@return the number of accounts having least the given balance
*/
public int count(double atLeast)
{
int matches = 0;
for (BankAccount a : accounts)
{
if (a.getBalance() >= atLeast) matches++; // Found a match
}
return matches;
}
/**
Finds a bank account with a given number.
@param accountNumber the number to find
@return the account with the given number, or null if there
is no such account
*/
public BankAccount find(int accountNumber)
{
for (BankAccount a : accounts)
{
if (a.getAccountNumber() == accountNumber) // Found a match
return a;
}
return null; // No match in the entire array list
}
/**
Gets the bank account with the largest balance.
@return the account with the largest balance, or null if the
bank has no accounts
*/
public BankAccount getMaximum()
{
if (accounts.size() == 0) return null;
BankAccount largestYet = accounts.get(0);
for (int i = 1; i < accounts.size(); i++)
{
BankAccount a = accounts.get(i);
if (a.getBalance() > largestYet.getBalance())
largestYet = a;
}
return largestYet;
}
private ArrayList accounts;
}
A driver class:
/**
This program tests the Bank class.
*/
public class BankTester
{
public static void main(String[] args)
{
Bank firstBankOfJava = new Bank();
firstBankOfJava.addAccount(new BankAccount(1001, 20000));
firstBankOfJava.addAccount(new BankAccount(1015, 10000));
firstBankOfJava.addAccount(new BankAccount(1729, 15000));
double threshold = 15000;
int c = firstBankOfJava.count(threshold);
System.out.println("Count: " + c);
System.out.println("Expected: 2");
int accountNumber = 1015;
BankAccount a = firstBankOfJava.find(accountNumber);
if (a == null)
System.out.println("No matching account");
else
System.out.println("Balance of matching account: " + a.getBalance());
System.out.println("Expected: 10000");
BankAccount max = firstBankOfJava.getMaximum();
System.out.println("Account with largest balance: "
+ max.getAccountNumber());
System.out.println("Expected: 1001");
}
}
Classwork:
Modify the Purse class to be a generic class and to use a for-each loop.
Homework:
Implement the following methods in the Purse class:
/**
Counts the number of coins in the purse
@return the number of coins
*/
public int count()
{
}
/**
Tests if the purse has a coin that matches
a given coin.
@param aCoin the coin to match
@return true if there is a coin equal to aCoin
*/
public boolean find(Coin aCoin)
{
}
/**
Counts the number of coins in the purse that match
a given coin.
@param aCoin the coin to match
@return the number of coins equal to aCoin
*/
public int count(Coin aCoin)
{
}
/**
Finds the coin with the largest value.
(Precondition: The purse is not empty)
@return a coin with maximum value in this purse
*/
Coin getMaximum()
{
}
The following code and concepts are for more in-depth knowledge of generics and type parameters.
A Generic Version of the Box Class
/**
* Generic version of the Box class.
* @param the type of the value being boxed
*/
public class Box {
// T stands for "Type"
private T t;
public void set(T t) { this.t = t; }
public T get() { return t; }
}
Invoking and Instantiating a Generic Type
To reference the generic Box class from within your code, you must perform a generic type invocation, which replaces T with some concrete value, such as Integer:
Box integerBox;
You can think of a generic type invocation as being similar to an ordinary method invocation, but instead of passing an argument to a method, you are passing a type argument — Integer in this case — to the Box class itself.
Like any other variable declaration, this code does not actually create a new Box object. It simply declares that integerBox will hold a reference to a “Box of Integer”, which is how Box is read.
An invocation of a generic type is generally known as a parameterized type.
To instantiate this class, use the new keyword, as usual, but place between the class name and the parenthesis:
Box integerBox = new Box();
The most commonly used type parameter names are:
E – Element (used extensively by the Java Collections Framework)
K – Key
N – Number
T – Type
V – Value
S,U,V etc. – 2nd, 3rd, 4th types
Chapter 6: Arrays and ArrayLists
Arrays of Objects
arrays as parameters
An entire array can be passed as a parameter to a method. Because an array is an object, when an entire array is passed as a parameter, a copy of the reference to the original array is passed.
A method that receives an array as a parameter can permanently change an element of the array because it is referring to the original element value. The method cannot permanently change the reference to the array itself because a copy of the original reference is sent to the method. These rules are consistent with the rules that govern any object type.
An element of an array can be passed to a method as well. If the element type is a primitive type, a copy of the value is passed. If that element is a reference to an object, a copy of the object reference is passed. As always, the impact of changes made to a parameter inside the method depends on the type of the parameter.
//********************************************************************
// GradeRange.java Author: Lewis/Loftus/Cocking
//
// Demonstrates the use of an array of String objects.
//********************************************************************
public class GradeRange
{
//-----------------------------------------------------------------
// Stores the possible grades and their numeric lowest value,
// then prints them out.
//-----------------------------------------------------------------
public static void main (String[] args)
{
String[] grades = {"A", "A-", "B+", "B", "B-", "C+", "C", "C-",
"D+", "D", "D-", "F"};
int[] cutoff = {95, 90, 87, 83, 80, 77, 73, 70, 67, 63, 60, 0};
for (int level = 0; level < cutoff.length; level++)
System.out.println (grades[level] + "\t" + cutoff[level]);
}
}
//********************************************************************
// NameTag.java Author: Lewis/Loftus/Cocking
//
// Demonstrates the use of command line arguments.
//********************************************************************
public class NameTag
{
//-----------------------------------------------------------------
// Prints a simple name tag using a greeting and a name that is
// specified by the user.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.println ();
System.out.println (" " + args[0]);
System.out.println ("My name is " + args[1]);
System.out.println ();
}
}
filling arrays of objects
We must always take into account an important characteristic of object arrays: The creation of the array and the creation of the objects that we store in the array are two separate steps.
When we declare an array of String objects, for example, we create an array that holds String references. The String objects themselves must be created separately.
The String objects are created using string literals in an initializer list, or, in the case of command-line arguments, they are created by the Java runtime environment.
This issue is demonstrated in the Tunes program and its accompanying classes. Listing 6.7 shows the Tunes class, which contains a main method that creates, modifies, and examines a compact disc (CD) collection. Each CD added to the collection is specified by its title, artist, purchase price, and number of tracks.
//********************************************************************
// Tunes.java Author: Lewis/Loftus/Cocking
//
// Driver for demonstrating the use of an array of objects.
//********************************************************************
public class Tunes
{
//-----------------------------------------------------------------
// Creates a CDCollection object and adds some CDs to it. Prints
// reports on the status of the collection.
//-----------------------------------------------------------------
public static void main (String[] args)
{
CDCollection music = new CDCollection ();
music.addCD ("By the Way", "Red Hot Chili Peppers", 14.95, 10);
music.addCD ("Come On Over", "Shania Twain", 14.95, 16);
music.addCD ("Soundtrack", "The Producers", 17.95, 33);
music.addCD ("Play", "Jennifer Lopez", 13.90, 11);
System.out.println (music);
music.addCD ("Double Live", "Garth Brooks", 19.99, 26);
music.addCD ("Greatest Hits", "Stone Temple Pilots", 15.95, 13);
System.out.println (music);
}
}
The CDCollection class contains an array of CD objects representing the collection.
It maintains a count of the CDs in the collection and their combined value.
It also keeps track of the current size of the collection array so that a larger array can be created if too many CDs are added to the collection.
The collection array is instantiated in the CDCollection constructor. Every time a CD is added to the collection (using the addCD method), a new CD object is created and a reference to it is stored in the collection array.
Each time a CD is added to the collection, we check to see whether we have reached the current capacity of the collection array. If we didn’t perform this check, an exception would eventually be thrown when we try to store a new CD object at an invalid index.
If the current capacity has been reached, the private increaseSize method is invoked, which first creates an array that is twice as big as the current collection array.
Each CD in the existing collection is then copied into the new array.
Finally, the collection reference is set to the larger array. Using this technique, we theoretically never run out of room in our CD collection.
The user of the CDCollection object (the main method) never has to worry about running out of space because it’s all handled internally.
//********************************************************************
// CDCollection.java Author: Lewis/Loftus/Cocking
//
// Represents a collection of compact discs.
//********************************************************************
import java.text.NumberFormat;
public class CDCollection
{
private CD[] collection;
private int count;
private double totalCost;
//-----------------------------------------------------------------
// Creates an initially empty collection.
//-----------------------------------------------------------------
public CDCollection ()
{
collection = new CD[100];
count = 0;
totalCost = 0.0;
}
//-----------------------------------------------------------------
// Adds a CD to the collection, increasing the size of the
// collection if necessary.
//-----------------------------------------------------------------
public void addCD (String title, String artist, double cost,
int tracks)
{
if (count == collection.length)
increaseSize();
collection[count] = new CD (title, artist, cost, tracks);
totalCost += cost;
count++;
}
//-----------------------------------------------------------------
// Returns a report describing the CD collection.
//-----------------------------------------------------------------
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String report = "******************************************\n";
report += "My CD Collection\n\n";
report += "Number of CDs: " + count + "\n";
report += "Total cost: " + fmt.format(totalCost) + "\n";
report += "Average cost: " + fmt.format(totalCost/count);
report += "\n\nCD List:\n\n";
for (int cd = 0; cd < count; cd++)
report += collection[cd].toString() + "\n";
return report;
}
//-----------------------------------------------------------------
// Doubles the size of the collection by creating a larger array
// and copying the existing collection into it.
//-----------------------------------------------------------------
private void increaseSize ()
{
CD[] temp = new CD[collection.length * 2];
for (int cd = 0; cd < collection.length; cd++)
temp[cd] = collection[cd];
collection = temp;
}
}
//********************************************************************
// CD.java Author: Lewis/Loftus/Cocking
//
// Represents a compact disc.
//********************************************************************
import java.text.NumberFormat;
public class CD
{
private String title, artist;
private double cost;
private int tracks;
//-----------------------------------------------------------------
// Creates a new CD with the specified information.
//-----------------------------------------------------------------
public CD (String name, String singer, double price, int numTracks)
{
title = name;
artist = singer;
cost = price;
tracks = numTracks;
}
//-----------------------------------------------------------------
// Returns a description of this CD.
//-----------------------------------------------------------------
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String description;
description = fmt.format(cost) + "\t" + tracks + "\t";
description += title + "\t" + artist;
return description;
}
}
An Object of a Wrapper Class
Wrapper objects can be used anywhere that objects are required instead of primitive type values. For example, you can collect a sequence of floating-point numbers in an ArrayList.
Conversion between primitive types and the corresponding wrapper classes is automatic. This process is called auto-boxing (even though auto-wrapping would have been more consistent).
For example, if you assign a number to a Double object, the number is automatically “put into a box”, namely a wrapper object.
Double d = 29.95; // auto-boxing; same as Double d = new Double(29.95);
Wrapper objects are automatically “unboxed” to primitive types.
double x = d; // auto-unboxing; same as double x = d.doubleValue();
ArrayList data = new ArrayList();
data.add(29.95);
double x = data.get(0);
The UML class diagram of the Tunes program.
Recall that the open diamond indicates aggregation (a has-a relationship). The cardinality of the relationship is also noted: a CDCollection object contains zero or more CD objects.
Classwork: Programming Projects 6.9
Arrays can be create with the “new” operator: int[] height = new int[11]
Arrays can also be created in using this format: int[] scores = {76, 87, 99}
The index operator [ ] performs automatic bounds checking
Beware of the off-by-one errors in a program
Either syntax int[] grades or int grades[] is correct
NOTE: The following programs and the pdf are stored in edmodo’s folder. Get familiar with all these programs and their algorithms to further develop assignments.
BasicArray
//********************************************************************
// BasicArray.java Author: Lewis/Loftus/Cocking
//
// Demonstrates basic array declaration and use.
//********************************************************************
public class BasicArray
{
final static int LIMIT = 15;
final static int MULTIPLE = 10;
//-----------------------------------------------------------------
// Creates an array, fills it with various integer values,
// modifies one value, then prints them out.
//-----------------------------------------------------------------
public static void main (String[] args)
{
int[] list = new int[LIMIT];
// Initialize the array values
for (int index = 0; index < LIMIT; index++)
list[index] = index * MULTIPLE;
list[5] = 999; // change one array value
for (int index = 0; index < LIMIT; index++)
System.out.print (list[index] + " ");
System.out.println ();
}
}
[collapse]
Primes
//********************************************************************
// Primes.java Author: Lewis/Loftus/Cocking
//
// Demonstrates the use of an initializer list for an array.
//********************************************************************
public class Primes
{
//-----------------------------------------------------------------
// Stores some prime numbers in an array and prints them.
//-----------------------------------------------------------------
public static void main (String[] args)
{
int[] primeNums = {2, 3, 5, 7, 11, 13, 17, 19};
System.out.println ("Array length: " + primeNums.length);
System.out.println ("The first few prime numbers are:");
for (int scan = 0; scan < primeNums.length; scan++)
System.out.print (primeNums[scan] + " ");
System.out.println ();
}
}
[collapse]
Printing an array of integers in reverse order:
ReverseOrder
//********************************************************************
// ReverseOrder.java Author: Lewis/Loftus/Cocking
//
// Demonstrates array index processing.
//********************************************************************
import java.util.Scanner;
public class ReverseOrder
{
//-----------------------------------------------------------------
// Reads a list of numbers from the user, storing them in an
// array, then prints them in the opposite order.
//-----------------------------------------------------------------
public static void main (String[] args)
{
double[] numbers = new double[10];
Scanner scan = new Scanner(System.in);
System.out.println ("The size of the array: " + numbers.length);
for (int index = 0; index < numbers.length; index++)
{
System.out.print ("Enter number " + (index+1) + ": ");
numbers[index] = scan.nextDouble();
}
System.out.println ("The numbers in reverse order:");
for (int index = numbers.length-1; index >= 0; index--)
System.out.print (numbers[index] + " ");
System.out.println ();
}
}
Output:
The size of the array: 10
Enter number 1: 18.36
Enter number 2: 48.9
Enter number 3: 53.3
Enter number 4: 21.9
Enter number 5: 34.7
Enter number 6: 12.5
Enter number 7: 78.4
Enter number 8: 98.1
Enter number 9: 99.0
Enter number 10: 37.9
The numbers in reverse order:
37.9 99.0 98.1 78.4 12.5 34.7 21.9 53.3 48.9 18.36
[collapse]
Letter counting
LetterCount
//********************************************************************
// LetterCount.java Author: Lewis/Loftus/Cocking
//
// Demonstrates the relationship between arrays and strings.
//********************************************************************
import java.util.Scanner;
public class LetterCount
{
//-----------------------------------------------------------------
// Reads a sentence from the user and counts the number of
// uppercase and lowercase letters contained in it.
//-----------------------------------------------------------------
public static void main (String[] args)
{
final int NUMCHARS = 26;
Scanner scan = new Scanner(System.in);
int[] upper = new int[NUMCHARS];
int[] lower = new int[NUMCHARS];
char current; // the current character being processed
int other = 0; // counter for non-alphabetics
System.out.println ("Enter a sentence:");
String line = scan.nextLine();
// Count the number of each letter occurence
for (int ch = 0; ch < line.length(); ch++)
{
current = line.charAt(ch);
if (current >= 'A' && current <= 'Z')
upper[current-'A']++;
else
if (current >= 'a' && current <= 'z')
lower[current-'a']++;
else
other++;
}
// Print the results
System.out.println ();
for (int letter=0; letter < upper.length; letter++)
{
System.out.print ( (char) (letter + 'A') );
System.out.print (": " + upper[letter]);
System.out.print ("\t\t" + (char) (letter + 'a') );
System.out.println (": " + lower[letter]);
}
System.out.println ();
System.out.println ("Non-alphabetic characters: " + other);
}
}
Output:
Enter a sentence:
In Casablanca, Humprey Bogart never says "Play it again, Sam."
Array length: 8
The first few prime numbers are:
2 3 5 7 11 13 17 19
Helpful notes for testing purposes:
Instead of entering manually input, you could put the data in a file like input.data. Take a look at an easy way to read data from a file:
import java.util.Scanner;
public class ScannerInTerminal
{
public static void main(String [] args)
{
Scanner sc = new Scanner(System.in);
String fromTerm = sc.next();
System.out.println(fromTerm);
}
}
Then you can run it in Terminal
mrseliaTerminal%: java ScannerInTerminal < input.txt
3.14159…
Classwork:
Programming Projects 6.1, 6.2, 6.4 and 6.5
Homework:
Short Answers 6.1, 6.2 and 6.3
Read pages 298 through 311
The Java Language
1. What is encapsulation and what is the purpose?
2. Explain abstractions. Give an example of an abstraction.
3. Give the code to concatenate two strings “hello” and “goodbye”.
4. List the escape sequences and the meaning.
5. Write the statement to print “Hello World” including the quotes.
5. List all primitive data types you know.
6. What is the difference between a character and a string.
7. Do you need to cast when assigning a double to an integer? why or why not?
8. Do you need to cast when assigning an integer to a double? why or why not?
9. Give an example of widening and narrowing type conversion for each.
10. What is the purpose of casting when using a casting operator in the case of narrowing type conversion.
11. What does “123456789”.substring(3,6) return?
12. Write a main method that prompts the use for two numbers, x and y, and it displays it back the following format: (x,y).
13. Write a code snipped to compare two strings, s1 and s2. If s1 comes first in the lexicographic order, then it will print “move two steps forward” else “move two steps backwards.
14. What is the result of 21 % 6 when evaluated in a java expression?
Object Oriented Design
1. What are classes like?
2. What is the content of an object variable?
3. Why the “= =” cannot be used to compare objects?
4. What is an instance of a class?
5. In the following code: BankAccount myAcct = new BankAccount(); Is myAcct an object of BankAccount?
6. What is the purpose of a constructor?
7. Can you have multiple constructors?
8. What is the return type of a constructor?
9. What does the operator new do?
10. What does it mean a string object is inmutable?
11. What is a wrapper class? What is autoboxing? Give clear examples.
Homework:
Do the self-review questions at the end of the chapter.
Reflect on this article: