ArrayList
and HashSet
and HashMap
:CSCE 145: Algorithmic Design I
ArrayList
and HashSet
and HashMap
:import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class PlotStock extends JPanel {
/**
* Initial Screen size.
*/
public static final int WIDTH = 640;
public static final int HEIGHT = 400;
/**
* Fetches stock data from google and prints it out to the
* console.
*/
private void getData(){
try {
//Get data on AAPL (Apple Computer) stock.
//To get data on other sticker symbols simply replace AAPL with your
// desired symbol, like GOOG.
URL data = new URL("http://www.google.com/finance/historical?q=AAPL&output=csv");
BufferedReader in = new BufferedReader(
new InputStreamReader(data.openStream()));
String inputLine;
//TODO: rather than printing them out, we need to pick out the
// closing prices and save them for later plotting.
while ((inputLine = in.readLine()) != null){
System.out.println(inputLine);
}
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("Uh Oh, I cannot reach the Internet.");
}
}
/**
* This method gets called when the class first gets create and also whenever the
* window needs to be redraw, like when the user changes its size, de-iconifies it,
* moves it, etc.
*/
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.black);
getData();
//Draw a line from 10,10 to the bottom right of the window.
//TODO: draw the line graph of the closing prices instead.
g2.drawLine(10,10, getWidth(), getHeight());
//Notice that getWidth() and getHeight() can be used to give us
// the width and height of the current window (which might be
// different from the original because the user changed it).
}
public static void main(String[] args) {
String symbol = JOptionPane.showInputDialog("Enter Ticker Symbol:");
if (symbol == null) System.exit(0); //quit if user hit Cancel
JFrame frame = new JFrame("Window"); //frame is the window
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PlotStock panel = new PlotStock(); //panel is the graphics area where we can draw
frame.add(panel); //put the panel inside the window
frame.setSize(WIDTH,HEIGHT); //set the window size to 640x400 pixels
frame.setVisible(true);
}
}
String.split(",",0)
is very useful for parsing the CSV file.getWidth()
and getHeight()
, as shown in the code. The rest is just a little bit of programming. You will need to find the max and min closing prices, and number of days of data, then scale these to fit the current window.import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* Triangle.java
* @author Jose M Vidal
* Created on Mar 19, 2012
*
*/
public class Triangle extends JPanel {
public void drawTriangle(Graphics2D g, int x1, int y1, int x2, int y2, int x3, int y3){
g.drawLine(x1, y1, x2, y2);
g.drawLine(x2, y2, x3, y3);
g.drawLine(x3, y3, x1, y1);
}
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.black);
drawTriangle(g2,1,640, 320,0, 640,640);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Window"); //frame is the window
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Triangle panel = new Triangle(); //panel is the graphics area where we can draw
frame.add(panel); //put the panel inside the window
frame.setSize(650,680); //set the window size to 640x640 pixels
frame.setVisible(true);
}
}
drawTriangle
method so that it takes as argument another variable, the level
. If the level is 0 it will draw the triangle exactly as it does now. one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifthteen sixteen seventeen eightteen nineteen twenty twentyone twentytwo twentythree twentyfour twentyfive twentysix ...and so on... one hundred and ninetyseven one hundred and ninetyeight one hundred and ninetynine two hundred two hundred and one two hundred and two two hundred and three two hundred and four two hundred and five two hundred and six two hundred and seven ...and so on... nine hundred and ninetynine thousand nine hundred and ninetyfive nine hundred and ninetynine thousand nine hundred and ninetysix nine hundred and ninetynine thousand nine hundred and ninetyseven nine hundred and ninetynine thousand nine hundred and ninetyeight nine hundred and ninetynine thousand nine hundred and ninetynine one million
Serializable
interface. The following video shows you how:1- I am thinking of his marrying 2- I am sure she is not 3- I am glad to find that 4- I am not acquainted with him 5- I am sick of Mr. Bingley," 6- I am sorry to hear _that_; 7- I am ! and it is 8- I am not afraid; for though 9- I am particularly acquainted with my ...and so on... 280- I am afraid; for what becomes 281- I am not indebted for my 282- I am more likely to want 283- I am happier even than Jane; 284- I am sure Wickham would like
Scanner.findWithinHorizon("I am",0)
will come in handy for this.I am sure: 36 I am afraid:15 I am not afraid:5
Date
class and a DateFormatException
class. The Date
class keeps the date in three private int member variables, called month, day, year. It has the following methods:Date(int month, int day, int year)
: is the constructortoString()
: returns the date in a String of the form 2/2/2002public static Date parseDate(String d) throws DateFormatException
: tries to parse the string d into a viable date. If it succeeds then it creates a new date and returns it. If it fails then it throws the DateFormatException. d is a viable date if it is in the form "m/d/y" where m is an integer between 1 and 12, d is an integer between 1 and 31, and y is an integer.public static void main(String[] args){
Date d = null;
Scanner keyboard = new Scanner(System.in);
boolean goodDate = false;
do {
System.out.print("Enter a date:");
String w = keyboard.next();
try{
d = Date.parseDate(w);
goodDate = true;
} catch (DateFormatException e){
System.out.println("Bad user! " + w + " is not a date I understand.");
}
} while (! goodDate);
System.out.println("Finally! You entered a well-formatted date: " + d);
}
Enter a date:chanchan Bad user! chanchan is not a date I understand. Enter a date:44/44/44 Bad user! 44/44/44 is not a date I understand. Enter a date:1/44/2012 Bad user! 1/44/2012 is not a date I understand. Enter a date:44/24/2012 Bad user! 44/24/2012 is not a date I understand. Enter a date:3-3-2012 Bad user! 3-3-2012 is not a date I understand. Enter a date:3/19/2012 Finally! You entered a well-formatted date: 3/19/2012
oe.occupation
file. Each line in this file lists a different occupation by first listing the occupation code, a space, then the English description, a space, then a number (1). Your program will need to first read all these occupations codes and descriptions into an array so it can then ask the user for which occupation he wants to know the total number of people employed.oe.data.0.Current
file contains all the data. It is a large file (266MB) and the .gov site is slow so, here is my copy. The oe.txt file describes the format of the data in this file in detail, but I will explain below what you need to do for this HW. The oe.data.0.Current
file looks likeseries_id year period value footnote_codes OEUM001018000000000000001 2010 S01 61790 OEUM001018000000000000002 2010 S01 2.2 OEUM001018000000000000003 2010 S01 16.72 OEUM001018000000000000004 2010 S01 34780
series_id (OEUM000040000000000000001)
can be broken out into:Code Value(Example) survey abbreviation = OE seasonal(code) = U area_code = 0000400 industry_code = 000000 occupation_code = 000000 datatype_code = 01
series_id
that starts with OEUS and have a datatype_code
(end with) of 01, which corresponds to "number of jobs". The occupation_code
corresponds to the code from the oe.occupation
file.oe.occupation
file. It will then show the user the list of all occupation codes, numbered, and ask him to pick one. It will then open up the oe.data.0.Current
file and add up the values (fourth column) of all the rows that with a series_id that starts with OEUS, ends with 01, and matches the user's chosen occupation code. Finally, it will print out this number. Here is a sample run:0 - All Occupations
1 - Management Occupations
2 - Chief Executives
3 - General and Operations Managers
....and so on.....
817 - Mine Shuttle Car Operators
818 - Tank Car, Truck, and Ship Loaders
819 - Material Moving Workers, All Other
Which of the occupations above do you need data for?
Enter number:77
Working......
17750 persons work as Actuaries in the US.
Enter number:66 Working...... 3294290 persons work as Computer and Mathematical Occupations in the US. Enter number:69 Working...... 335330 persons work as Computer Programmers in the US. Enter number:70 Working...... 499880 persons work as Software Developers, Applications in the US. Enter number:94 Working...... 144870 persons work as Electrical Engineers in the US. Enter number:101 Working...... 223470 persons work as Mechanical Engineers in the US. Enter number:119 Working...... 1072400 persons work as Life, Physical, and Social Science Occupations in the US. Enter number:146 Working...... 3360 persons work as Sociologists in the US. Enter number:1 Working...... 6066780 persons work as Management Occupations in the US. Enter number:295 Working...... 7394880 persons work as Healthcare Practitioners and Technical Occupations in the US.
oe.occupation
file, along with an Occupation class which holds just one occupation: its name and its code.public class Boat extends Ship {
private int seaWorthinessRating;
public Boat(double maxSpeed) {
super(maxSpeed);
seaWorthinessRating = 33;
}
public Boat(double maxSpeed, int rating) {
super(maxSpeed);
seaWorthinessRating = rating;
}
public String toString(){
return "mp=" + maxSpeed + " seaworth=" + seaWorthinessRating;
}
}
public class SailBoat extends Boat {
public String toString(){
return "Sailboat";
}
}
public class Ship {
protected double maxSpeed;
public Ship(double maxSpeed){
this.maxSpeed = maxSpeed;
}
public String toString(){
return "maxSpeed=" + maxSpeed;
}
public static void main(String[] args){
Ship s1 = new Ship(1);
System.out.println(s1);
Ship s2 = new Boat(2,66);
Ship s22 = new Boat(8);
System.out.println(s2);
System.out.println(s22);
SailBoat s3 = new SailBoat(3,77);
System.out.println(s3);
Ship s4 = (Ship)s3;
System.out.println(s4);
}
}
public interface Drinkable {Answer: An interface cannot implement a method.
public void drink();
public boolean isEmpty(){ return false;}
}
public class RedBull implements Drinkable {
private int size;
public RedBull(int size){
this.size = size;
}
public void drink(){
System.out.println("Yuuuuuckkkkk");
}
public boolean isEmpty(){
return true;
}
}
a
and returns a new array, lets call it r
, where r[0]
has the sum of a[0] + a[1]
, and r[1]
has the sum of a[2] + a[3]
, and so on. You can assume that the length of a
is even.public static int[] everyOther(int[] a){
int[] result = new int[a.length/2];
for (int i = 0; i < a.length; i+=2) {
result[i/2] = a[i] + a[i+1];
}
return result;
}
public class Plant {Implement the missing
private String name;
public Plant(String name){
this.name = name;
}
public String getName(){
return name;
}
public static void main(String[] args){
Plant[] garden = new Plant[3];
garden[0] = new Plant("Vine");
//Create a Rosemary plant with the name Vanity
// it will have 1024 leaves by default
garden[1] = new Rosemary("Vanity");
//This one will have 2048 leaves
garden[2] = new Rosemary("Pride", 2048);
for (Plant p: garden){
System.out.println(p.getName()); //print their names
}
//getRosemaries() returns the total number of rosemaries
// that have been created.
System.out.println("There are " + Rosemary.getNumRosemaries()
+ " rosemary plants.");
Rosemary r = new Rosemary("Loathing");
System.out.println(r.getName());
System.out.println("There are " + Rosemary.getNumRosemaries()
+ " rosemary plants.");
}
}
Rosemary
class so that when we run the code above it will print:Vine Rosemary:Vanity numLeaves=1024 Rosemary:Pride numLeaves=2048 There are 2 rosemary plants. Rosemary:Loathing numLeaves=1024 There are 3 rosemary plants.
Rosemary
must have.Answer:
public class Rosemary extends Plant {
private int numLeaves;
private static int numCreated = 0;
public Rosemary(String name) {
super("Rosemary:" + name );
numLeaves = 1024;
numCreated++;
}
public Rosemary(String name, int numLeaves) {
super("Rosemary:" + name );
this.numLeaves= numLeaves;
numCreated++;
}
public String getName(){
return super.getName() + " numLeaves=" + numLeaves;
}
public static int getNumRosemaries(){
return numCreated;
}
}
public class Boot extends Shoe {
protected int height;
public Boot(int height){
super(9);
this.height = height;
}
public Boot(int height, int size){
super(size);
this.height = height;
}
}
public class Ugg extends Boot {
public Ugg(int height, int size) {
super(height,size);
height--;
}
public String toString(){
return "Ugg size=" + super.toString() + " height=" + height;
}
}
public class Shoe {
private int size;
public Shoe(){
size = 7;
}
public Shoe(int size) {
this.size = size;
}
public String toString() {
return "Shoe [size=" + size + "]";
}
public static void main(String[] args) {
Shoe s1 = new Shoe();
System.out.println(s1);
Boot s3 = new Ugg(7,9);
System.out.println(s3);
Boot s4 = new Boot(5,15);
System.out.println(s4);
Ugg s5 = new Ugg(9,16);
System.out.println(s5);
Boot s6 = (Boot)s5;
System.out.println(s6);
}
}
public interface Playable{Answer: An interface cannot implement a method.
public void play() {
super();
};
public int timeLeft();
}
public class Media {
protected String title;
public Media(String title){
this.title = title;
}
}
public class Song extends Media implements Playable{
protected int runningTime;
public Song(String name, int runningTime){
super(name);
this.runningTime = runningTime;
}
public void play(){
System.out.println("Playing....");
}
public int timeLeft(){
return runningTime - 10;
}
}
a
and returns a new array, lets call it r
, where r[0]
contains the sum of a[0]
and a[last index in a]
, r[1]
contains the sum of a[1]
and a[last index in a minus 1]
, and so on. You can assume that the length of a
is even.Answer:
public static int[] fold(int[] a){
int[] result = new int[a.length/2];
for (int i = 0; i < a.length / 2; i++) {
result[i] = a[i] + a[a.length - 1 - i];
}
return result;
}
public interface LeafEater {
public void eatLeaf();
}
public class Mammal {
protected int numToes;
protected static int count = 0;
public Mammal(){
numToes = 5;
count++;
}
public String toString(){
return "Mammal with " + numToes + " toes.";
}
public static void main(String[] args) {
Mammal[] animals = new Mammal[4];
animals[0] = new Mammal();
//Creates a giraffe with 8 toes and height of 10.0 feet.
animals[1] = new Giraffe();
//Creates a giraffe with 5 toes and height of 14.6 feet.
animals[2] = new Giraffe(14.6);
//Creates a giraffe with 8 toes and height of 10.0 feet.
animals[3] = new Giraffe();
for (Mammal m : animals){
System.out.println(m);
}
//getCount() returns the number of Mammals that have been created.
System.out.println("There are " + Giraffe.getCount() + " mammals");
}
}
Giraffe
class so that when we run the code above it will print:Mammal with 5 toes. Mammal with 8 toes.-- Giraffe: 10.0 feet. Mammal with 5 toes.-- Giraffe: 14.6 feet. Mammal with 8 toes.-- Giraffe: 10.0 feet. There are 4 mammalsSee the comments in the code for hints on what the various methods and attributes
Giraffe
must have.Answer:
public class Giraffe extends Mammal implements LeafEater{
private double height;
public Giraffe(){
super();
height = 10;
numToes = 8;
}
public Giraffe(double height){
super();
this.height = height;
}
public String toString(){
return super.toString() + "-- Giraffe: " + height + " feet.";
}
public static int getCount(){
return count;
}
public void eatLeaf() {
System.out.println("Yummm, leaves are good.");
}
}
WordList
which is an infinitely expanding container of Strings. The WordList
class will keep an array of Strings which starts at a size of 2 (the first array created is of size 2) but then doubles in size whenever the user of the class tries to add
an element which would not fit in the current wordlist. For example, the first time it doubles will be when trying to add the third word, then on the fifth, then on the ninth, and so on.WordList
will implement the following methods:add(String w)
: adds the string w
to the word list, and expands the size of the underlying array if needed, by doubling its size. It returns the WordList.size()
: returns the number of words in the WordListlength()
: returns the length of the arraytoString()
: all the words, separated by spaces.WordList
implements the following interface:public interface Iterator {
/**
* Resets the iterator to point to the first word.
*/
public void resetIterator();
/**
* Returns the next word. If we are beyond the end then return null.
* Also moves the iterator to the next word.
* @return the next word or null.
*/
public String getNext();
/**
* @return true if there are still words to iterate over.
* false if we have reached the end
*/
public boolean hasNext();
}
public static void main(String[] args) {prints out
//Test adding words
WordList l = new WordList();
System.out.println("There are " + l.size() + " words.");
System.out.println("The words array is of length " + l.length() + ".");
l.add("We").add("are").add("the").add("priests").add("of");
l.add("The").add("Temples").add("of").add("Syrinx");
System.out.println(l);
System.out.println("There are " + l.size() + " words.");
System.out.println("The words array is of length " + l.length() + ".");
l.add("Our").add("great").add("computers").add("fill").add("the").add("hallowed").add("halls");
System.out.println(l);
System.out.println("There are " + l.size() + " words.");
System.out.println("The words array is of length " + l.length() + ".");
//Test REALLY big word lists
for (int i = 0; i < 10000000; i++) {
l.add("Rush");
}
System.out.println("There are " + l.size() + " words.");
System.out.println("The words array is of length " + l.length() + ".");
//Test the iterator
System.out.println("--Testing the iterator");
l = new WordList();
l.add("We").add("have").add("assumed").add("control");
l.add("There").add("is").add("trouble").add("with").add("the").add("trees");
l.resetIterator();
while (l.hasNext()){
String w = l.getNext();
System.out.println(w);
}
}
There are 0 words. The words array is of length 2. We are the priests of The Temples of Syrinx There are 9 words. The words array is of length 16. We are the priests of The Temples of Syrinx Our great computers fill the hallowed halls There are 16 words. The words array is of length 16. There are 10000016 words. The words array is of length 16777216. --Testing the iterator We have assumed control There is trouble with the trees