Commit b59df3cd by Adam Gerber

Merge branch 'lab07a'

parents 9404c08f 14a533ea
package lec07.glab.casting; package lec07.glab.casting;
import java.awt.*;
/** /**
* Created with IntelliJ IDEA. * Created with IntelliJ IDEA.
* User: ag * User: ag
...@@ -37,7 +39,7 @@ public class CastObjectsDriver { ...@@ -37,7 +39,7 @@ public class CastObjectsDriver {
//With reflection, we can see that we are NOT changing the object's type, it's still a Double, only now it's //With reflection, we can see that we are NOT changing the object's type, it's still a Double, only now it's
//being stored in a superlcass reference which restricts the of methods we can call on the reference //being stored in a superlcass reference which restricts the of methods we can call on the reference
//This is an automatic promotion, so the cast here is redundant //This is an automatic promotion, so the cast here is redundant
Number numMe = (Number) dubMe; Number numMe = dubMe;
System.out.println("A Number reference pointing to same Double object:"); System.out.println("A Number reference pointing to same Double object:");
System.out.println(numMe.getClass().toString()); System.out.println(numMe.getClass().toString());
//one of the methods we can call from the Number reference //one of the methods we can call from the Number reference
...@@ -58,7 +60,7 @@ public class CastObjectsDriver { ...@@ -58,7 +60,7 @@ public class CastObjectsDriver {
System.out.println("numMe and dubMe both point to the same object in memory space: " + (numMe == dubMe)); System.out.println("numMe and dubMe both point to the same object in memory space: " + (numMe == dubMe));
System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
System.out.println(Double.valueOf((Double) comMe));
//Now let's cast this to an Object //Now let's cast this to an Object
//This is an automatic promotion, so the cast here is redundant //This is an automatic promotion, so the cast here is redundant
Object objMe = (Object) comMe; Object objMe = (Object) comMe;
...@@ -91,13 +93,15 @@ public class CastObjectsDriver { ...@@ -91,13 +93,15 @@ public class CastObjectsDriver {
//toggle uncomment/comment to show compile-time error //toggle uncomment/comment to show compile-time error
//Rectangle recMe = (Rectangle) numMe; //Rectangle recMe = (Rectangle) numMe;
//However, if we try to cast comMe to a Rectangle (Rectangle implements Comparable) the compiler will NOT complain, but of course, we will still throw ClassCastException //However, if we try to cast comMe to a Rectangle (Rectangle implements Comparable) the compiler will NOT complain, but of course, we will still throw ClassCastException
//because the underlying object stored in comMe is still of type Double, and Rectangle is not in Double's class hierarchy. //because the underlying object stored in comMe is still of type Double, and Rectangle is not in Double's class hierarchy.
//toggle uncomment/comment this code below to throw a ClassCastException //toggle uncomment/comment this code below to throw a ClassCastException
// Rectangle recMeAgain = (Rectangle) comMe; // Rectangle recMeAgain = (Rectangle) comMe;
System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
//Let's go full circle. Casting-down is trivial. //Let's go full circle. Casting-down is trivial. When you cast down, you are actually opening the aperture.
//The underlying object that objMe points to is of type Double. If it weren't of type Double, we would get a ClassCastException //The underlying object that objMe points to is of type Double. If it weren't of type Double, we would get a ClassCastException
//We are effectively widening the filter to see all the methods of the original Double object //We are effectively widening the filter to see all the methods of the original Double object
Double dubMeDown = (Double) objMe; Double dubMeDown = (Double) objMe;
......
...@@ -21,34 +21,45 @@ public class CastPrimitivesDriver { ...@@ -21,34 +21,45 @@ public class CastPrimitivesDriver {
//if we read the above from right-to-left, we get //if we read the above from right-to-left, we get
//2^0 + 2^1 + 2^2 + 0 + 2^4 + 0 + 0 + 2^7 + 0 etc, which == 151 //2^0 + 2^1 + 2^2 + 0 + 2^4 + 0 + 0 + 2^7 + 0 etc, which == 151
short sMe = 151; short sMe = 407;
// short sMe = 151;
//Rather than pass the primitive directly into println, I'm going to use the wrapper class .valueOf(), which enforces the type //Rather than pass the primitive directly into println, I'm going to use the wrapper class .valueOf(), which enforces the type
System.out.println(Short.valueOf(sMe)); System.out.println("Short value of sMe : " + Short.valueOf(sMe));
//Let's promote this to an int which is a 32-bit signed integer ranging from -2^31 to 2^31 - 1 //Let's promote this to an int which is a 32-bit signed integer ranging from -2^31 to 2^31 - 1
int nMe = (int)sMe; int nMe = sMe;
//no problem, we don't really need all the precision, but memory is cheap, and the value stays the same. //no problem, we don't really need all the precision, but memory is cheap, and the value stays the same.
//when we copy the bits, we just put those bits into an 32-bit int like so -> //when we copy the bits, we just put those bits into an 32-bit int like so ->
//0 0 0 0 0 0 0 0 1 0 0 1 0 1 1 1 //upcasting is automatic (no cast required) and looses no precision
//0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 1 1 1
System.out.println(Integer.valueOf(nMe)); //0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 0 1 1 1
//0 0 0 0 0 0 0 1 1 0 0 1 0 1 1 1
System.out.println("After upcasting, int value of sMe : " + Integer.valueOf(nMe));
//and the original value stored in sMe is unchanged. //and the original value stored in sMe is unchanged.
System.out.println(Short.valueOf(sMe)); System.out.println("Short value of sMe : " + Short.valueOf(sMe));
//Let's demote this to an byte which is an 8-bit signed integer ranging from -128 to 127 //Let's demote this to an byte which is an 8-bit signed integer ranging from -128 to 127
//notice that 151 is out of this range, so when you copy the bits over, you will get erroneous results. //notice that 407 is out of this range, so when you copy the bits over, you will get erroneous results.
//downcasting requires a cast and you loose precision and potentially erroneous results.
//you flipped the sign-bit, so now, the result is -128 + 1 + 2 + 4 + 16, == -105. This is obviously erroenous.
//0 0 0 0 0 0 0 1 1 0 0 1 0 1 1 1
// 1 0 0 1 0 1 1 1
byte yMe = (byte) sMe; byte yMe = (byte) sMe;
System.out.println(Byte.valueOf(yMe)); System.out.println("After downcasting, byte value of sMe : " + Byte.valueOf(yMe));
//If we cast to a double (64-bit floating point value), we lose no precision. The number just becomes 151.0 //If we cast to a double (64-bit floating point value), we lose no precision. The number just becomes 151.0
double dMe = (double) sMe; double dMe = (double) sMe;
//when we use the == operator on primitives, we are not checking for memory addresses, but rather values //when we use the == operator on primitives, we are not checking for memory addresses, but rather values
System.out.println("These numbers, 151 and 151.0 are numerically equivalent : " + (sMe == dMe)); System.out.println("These numbers, 407 and 407.0 are numerically equivalent : " + (sMe == dMe));
System.out.println("#################################################################################"); System.out.println("#################################################################################");
......
package lec07.glab.jpanel_gui;
/**
* Created with IntelliJ IDEA.
* User: ag
* Date: 11/16/13
* Time: 10:16 AM
* To change this template use File | Settings | File Templates.
*/
public class Card {
//public static enum
public static enum Suit {
CLUBS('C'), DIAMONDS('D'), HEARTS('H'), SPADES('S');
private char value;
//you MUST make this constructor private!
private Suit(char value) {
this.value = value;
}
public char getValue(){
return value;
}
}
//instance members
private char mFace;
private Suit mSuit;
//constructor
public Card(char face, Suit suit) {
mFace = face;
mSuit = suit;
}
@Override
public String toString() {
return String.valueOf(mFace) + mSuit.getValue();
}
//getters and setters
public char getFace() {
return mFace;
}
public void setFace(char face) {
mFace = face;
}
public Suit getSuit() {
return mSuit;
}
public void setSuit(Suit suit) {
mSuit = suit;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="lec07.glab.jpanel_gui.MockTable">
<grid id="27dc6" binding="mPanel" layout-manager="GridLayoutManager" row-count="2" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="20" y="20" width="500" height="400"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<grid id="c799e" binding="mPanelPlayer" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children/>
</grid>
<component id="cd885" class="javax.swing.JButton" binding="mButtonShow">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Show Cards"/>
</properties>
</component>
</children>
</grid>
</form>
package lec07.glab.jpanel_gui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
/**
* Created with IntelliJ IDEA.
* User: ag
* Date: 11/16/13
* Time: 10:06 AM
* To change this template use File | Settings | File Templates.
*/
public class MockTable {
private JPanel mPanel;
private JButton mButtonShow;
private JPanel mPanelPlayer;
private ArrayList<Card> crdHands;
public static void main(String[] args) {
JFrame frame = new JFrame("MockTable");
frame.setContentPane(new MockTable().mPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.setSize(400, 300);
}
//pass in the graphics context of the jPanel you want to draw on
protected void drawCards(Graphics g) {
BufferedImage bufferedImage;
//use this counter to position the cards horizontally
int nXPos = 10;
for (Card card : crdHands) {
bufferedImage = SoundImageUtils.genBuffImage("/src/lec07/glab/jpanel_gui/imgs/" + card + ".png");
//nc = x-pos, 100 = y-pos
g.drawImage(bufferedImage, nXPos, 100, null);
nXPos = nXPos +25;
}
}
public MockTable() {
//initialization
crdHands = new ArrayList<Card>();
crdHands.add(new Card('9', Card.Suit.SPADES));
crdHands.add(new Card('T', Card.Suit.SPADES));
crdHands.add(new Card('J', Card.Suit.SPADES));
crdHands.add(new Card('Q', Card.Suit.SPADES));
crdHands.add(new Card('K', Card.Suit.SPADES));
//eventlisteners
mButtonShow.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
drawCards(mPanelPlayer.getGraphics());
}
});
}
}
package lec07.glab.jpanel_gui;
import javax.imageio.ImageIO;
import javax.sound.sampled.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
//http://stackoverflow.com/questions/2416935/how-to-play-wav-files-with-java/2417088#2417088
public class SoundImageUtils {
private static final int BUFFER_SIZE = 128000;
private static File soundFile;
private static AudioInputStream audioStream;
private static AudioFormat audioFormat;
private static SourceDataLine sourceLine;
/**
* @param filename the name of the file that is going to be played
*/
public static void playSound(String filename){
String strPath = System.getProperty("user.dir") + filename;
//String strPath = filename ;
try {
soundFile = new File(strPath);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
try {
audioStream = AudioSystem.getAudioInputStream(soundFile);
} catch (Exception e){
e.printStackTrace();
System.exit(1);
}
audioFormat = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
try {
sourceLine = (SourceDataLine) AudioSystem.getLine(info);
sourceLine.open(audioFormat);
} catch (LineUnavailableException e) {
e.printStackTrace();
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
sourceLine.start();
int nBytesRead = 0;
byte[] abData = new byte[BUFFER_SIZE];
while (nBytesRead != -1) {
try {
nBytesRead = audioStream.read(abData, 0, abData.length);
} catch (IOException e) {
e.printStackTrace();
}
if (nBytesRead >= 0) {
@SuppressWarnings("unused")
int nBytesWritten = sourceLine.write(abData, 0, nBytesRead);
}
}
sourceLine.drain();
sourceLine.close();
}
public static BufferedImage genBuffImage(String strRelativeFilePath){
String strPathImg= System.getProperty("user.dir")+ strRelativeFilePath;
File filImg = new File(strPathImg);
BufferedImage bufferedImage = null;
try {
bufferedImage = ImageIO.read(filImg);
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return bufferedImage;
}
public static BufferedImage genBuffImage(String strRelativeFilePath, int nWidth, int nHeight){
String strPathImg= System.getProperty("user.dir")+ strRelativeFilePath;
File filImg = new File(strPathImg);
BufferedImage bufferedImage = null;
try {
bufferedImage = ImageIO.read(filImg);
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return scaleImage(bufferedImage, nWidth, nHeight);
}
//method found on stackoverflow.com, re-implemented here
private static BufferedImage scaleImage(BufferedImage img, int nWidth, int nHeight) {
BufferedImage newImage = new BufferedImage(nWidth, nHeight,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = newImage.createGraphics();
try {
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g.setBackground(new Color(0,0,0));
g.clearRect(0, 0, nWidth, nHeight);
g.drawImage(img, 0, 0, nWidth, nHeight, null);
} finally {
g.dispose();
}
return newImage;
}
}
\ No newline at end of file
...@@ -7,7 +7,7 @@ public class RecursionDriver { ...@@ -7,7 +7,7 @@ public class RecursionDriver {
*/ */
public static void main(String[] args) { public static void main(String[] args) {
System.out.println(myFactorialRec(5)); System.out.println(myFactorialRec(12));
System.out.println(myFactorialIter(5)); System.out.println(myFactorialIter(5));
testIsPalindrome("A man, a plan, a canal, Panama!"); testIsPalindrome("A man, a plan, a canal, Panama!");
......
...@@ -12,7 +12,6 @@ import java.text.DecimalFormat; ...@@ -12,7 +12,6 @@ import java.text.DecimalFormat;
public class Coin { public class Coin {
private double mValue; private double mValue;
private static DecimalFormat sDecimalFormat = new DecimalFormat("$0.00");
public Coin(double value) { public Coin(double value) {
mValue = value; mValue = value;
...@@ -52,6 +51,6 @@ public class Coin { ...@@ -52,6 +51,6 @@ public class Coin {
@Override @Override
public String toString(){ public String toString(){
return sDecimalFormat.format(getValue()); return VendMachine.sDecimalFormat.format(getValue());
} }
} }
package lec07.glab.vend; package lec07.glab.vend;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
import java.util.Scanner; import java.util.Scanner;
/** /**
...@@ -18,7 +19,7 @@ public class Driver { ...@@ -18,7 +19,7 @@ public class Driver {
VendMachine vndMachine = new VendMachine(); VendMachine vndMachine = new VendMachine();
ArrayList<Product> prdProducts = new ArrayList<>(); List<Product> prdProducts = new ArrayList<>();
prdProducts.add(new Product("Heath", 0.75)); prdProducts.add(new Product("Heath", 0.75));
prdProducts.add(new Product("PayDay", 0.75)); prdProducts.add(new Product("PayDay", 0.75));
prdProducts.add(new Product("Reces", 0.75)); prdProducts.add(new Product("Reces", 0.75));
...@@ -48,7 +49,7 @@ public class Driver { ...@@ -48,7 +49,7 @@ public class Driver {
System.out.println(vndMachine.showSelection()); System.out.println(vndMachine.showSelection());
strSelect = makeSelection(); strSelect = makeSelection();
if (strSelect.equalsIgnoreCase("AABBCC")){ if (strSelect.equalsIgnoreCase("AABBCC")){
ArrayList<Coin> conCashOuts = vndMachine.cashOut(); List<Coin> conCashOuts = vndMachine.cashOut();
System.out.println("Jackpot!"); System.out.println("Jackpot!");
for (Coin conCashOut : conCashOuts) { for (Coin conCashOut : conCashOuts) {
System.out.println(conCashOut); System.out.println(conCashOut);
...@@ -60,7 +61,7 @@ public class Driver { ...@@ -60,7 +61,7 @@ public class Driver {
System.out.println("Thank you and Enjoy: " + prdProduct); System.out.println("Thank you and Enjoy: " + prdProduct);
else { else {
System.out.print("You inserted " + vndMachine.howMuchInserted() + " : Insufficient coins or out of stock"); System.out.print("You inserted " + vndMachine.howMuchInserted() + " : Insufficient coins or out of stock");
ArrayList<Coin> conReturns = vndMachine.returnCoins(); List<Coin> conReturns = vndMachine.returnCoins();
System.out.println(", here is your money back: "); System.out.println(", here is your money back: ");
for (Coin conReturn : conReturns) { for (Coin conReturn : conReturns) {
System.out.println(conReturn); System.out.println(conReturn);
......
...@@ -13,7 +13,6 @@ public class Product { ...@@ -13,7 +13,6 @@ public class Product {
private String mDesc; private String mDesc;
private double mPrice; private double mPrice;
private static DecimalFormat sDecimalFormat = new DecimalFormat("$0.00");
public Product(String desc, double price) { public Product(String desc, double price) {
mDesc = desc; mDesc = desc;
...@@ -38,7 +37,7 @@ public class Product { ...@@ -38,7 +37,7 @@ public class Product {
@Override @Override
public String toString() { public String toString() {
return mDesc + " " + sDecimalFormat.format(mPrice); return mDesc + " " + VendMachine.sDecimalFormat.format(mPrice);
} }
} }
...@@ -2,6 +2,7 @@ package lec07.glab.vend; ...@@ -2,6 +2,7 @@ package lec07.glab.vend;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.TreeMap; import java.util.TreeMap;
...@@ -50,12 +51,12 @@ public class VendMachine { ...@@ -50,12 +51,12 @@ public class VendMachine {
//cash-out //cash-out
//vend //vend
//show products available //show products available
private static DecimalFormat sDecimalFormat = new DecimalFormat("$0.00"); public static DecimalFormat sDecimalFormat = new DecimalFormat("$0.00");
//hold the vending machine's bank //hold the vending machine's bank
private ArrayList<Coin> mBanks; private List<Coin> mBanks;
//hold user's money until vending //hold user's money until vending
private ArrayList<Coin> mPurchaseMoneys; private List<Coin> mPurchaseMoneys;
private Map<String, Product[]> mapProducts; private Map<String, Product[]> mapProducts;
...@@ -71,7 +72,7 @@ public class VendMachine { ...@@ -71,7 +72,7 @@ public class VendMachine {
} }
public void stockMe(ArrayList<Product> prdProducts){ public void stockMe(List<Product> prdProducts){
//for each row //for each row
//for each col //for each col
...@@ -144,7 +145,7 @@ public class VendMachine { ...@@ -144,7 +145,7 @@ public class VendMachine {
} }
public void insertCoins(ArrayList<Coin> conPassed){ public void insertCoins(List<Coin> conPassed){
for (Coin con : conPassed) { for (Coin con : conPassed) {
mPurchaseMoneys.add(con); mPurchaseMoneys.add(con);
} }
...@@ -153,7 +154,7 @@ public class VendMachine { ...@@ -153,7 +154,7 @@ public class VendMachine {
} }
public void insertCoins(String strCoinValue){ public void insertCoins(String strCoinValue){
ArrayList<Coin> conCoins = new ArrayList<>(); List<Coin> conCoins = new ArrayList<>();
String[] strCoins = strCoinValue.split(" "); String[] strCoins = strCoinValue.split(" ");
for (String strCoin : strCoins) { for (String strCoin : strCoins) {
...@@ -216,14 +217,14 @@ public class VendMachine { ...@@ -216,14 +217,14 @@ public class VendMachine {
} }
public ArrayList<Coin> returnCoins(){ public List<Coin> returnCoins(){
ArrayList<Coin> conTemps = mPurchaseMoneys; List<Coin> conTemps = mPurchaseMoneys;
mPurchaseMoneys = new ArrayList<>(); mPurchaseMoneys = new ArrayList<>();
return conTemps; return conTemps;
} }
public ArrayList<Coin> cashOut(){ public List<Coin> cashOut(){
ArrayList<Coin> conTemp = mBanks; List<Coin> conTemp = mBanks;
//reset the bank //reset the bank
mBanks = new ArrayList<>(); mBanks = new ArrayList<>();
return conTemp; return conTemp;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment