Java Programming
Implement an auction application with the following features/functionality:
Inputs for an item and minimum bid amount.
Inputs for bidder name, bid amount and maximum bid. You will implement a class called Bid to
hold this information.
Label controls to show the current high bidder’s name, bid amount and maximum bid. For bid
amounts, you may assume all bids will be a whole dollar value just to simplify things a bit.
A list box to show all entries when the auction is over. You will use the pop() method to retrieve
each bid off the stack and display it. This feature is intended more for test/debug purposes.
You will implement a Stack class that will keep the highest bid at the top of the stack. It must
have the classic stack operations of push() to place an item on the stack, pop() to remove the top
item from the stack, and top() to view the top item on the stack but not remove it. You may use a
linked list of your own design, an array, or the built-in Java Array List or Linked List classes as
the underlying data structure. You may also add an item count property if you want.
The auction will work by the following rules:
When the initial bid is made, it must be greater than or equal to the item’s minimum bid amount
to be placed on the stack.
When another bid is made that is greater than the current high bidder’s maximum bid, that bid
will be pushed to the top of the stack and become the new highest bid.
If another bid is made that is greater than the current high bid but less than or equal to the
current high bidder’s maximum amount, the current high bidder’s bid will be raised to match but
the new bid will not be placed on the stack.
Your application should have a message box or label to indicate the status of the bid operation.
There is no limit on the number of bids.
Solution
// To import features as \'Panel, Button, Label, TextArea, TextField, Color\', etc.
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
// In this program, \"this.\" is used instead of \"this.getContentPane().\" in Auction.init() uses;
class Bidacution
{
public static void main (String[] args)
{ Frame gameapp = new Frame (\"AUCTION by Henry C. Joy\");
gameapp.setSize (750, 560); // larger than actual applet -- allow for edges
gameapp.addWindowListener (new WindowCloser());
Auction display = new Auction();
display.init();
gameapp.add (display);
gameapp.setVisible (true);
}
private static class WindowCloser extends java.awt.event.WindowAdapter
{ public void windowClosing (java.awt.event.WindowEvent e)
{ System.exit (0);
}}
}
// The MAIN method of the software (the init method): using 20 + classes.
public class Auction extends java.applet.Applet // every Applet is a Panel
{
public static final int UNIT = 5; // difference between 2 consec. bids
public static final int BREAK = 5; // separate first 5 from last 4
public static final String REPEAT = \"repeat game\";
// VIEW objects
private Panel boardPanel = new Panel();
p.
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdfudit652068
Working with Layout Managers. Notes: 1. In part 2, note that the Game class inherits from
JPanel. Therefore, the panel you are asked to add to the center of the content pane is the \"game\"
object. 2. In part 4, at the end of the function, call validate(). This is not mentioned in the book,
but it is mentioned in the framework comments.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Game extends JPanel
{
private JButton [][] squares;
private TilePuzzle game;
public Game( int newSide )
{
game = new TilePuzzle( newSide );
setUpGameGUI( );
}
public void setUpGame( int newSide )
{
game.setUpGame( newSide );
setUpGameGUI( );
}
public void setUpGameGUI( )
{
removeAll( ); // remove all components
setLayout( new GridLayout( game.getSide( ),
game.getSide( ) ) );
squares = new JButton[game.getSide( )][game.getSide( )];
ButtonHandler bh = new ButtonHandler( );
// for each button: generate button label,
// instantiate button, add to container,
// and register listener
for ( int i = 0; i < game.getSide( ); i++ )
{
for ( int j = 0; j < game.getSide( ); j++ )
{
squares[i][j] = new JButton( game.getTiles( )[i][j] );
add( squares[i][j] );
squares[i][j].addActionListener( bh );
}
}
setSize( 300, 300 );
setVisible( true );
}
private void update( int row, int col )
{
for ( int i = 0; i < game.getSide( ); i++ )
{
for ( int j = 0; j < game.getSide( ); j++ )
{
squares[i][j].setText( game.getTiles( )[i][j] );
}
}
if ( game.won( ) )
{
JOptionPane.showMessageDialog( Game.this,
\"Congratulations! You won!\ Setting up new game\" );
// int sideOfPuzzle = 3 + (int) ( 4 * Math.random( ) );
// setUpGameGUI( );
}
}
private class ButtonHandler implements ActionListener
{
public void actionPerformed( ActionEvent ae )
{
for( int i = 0; i < game.getSide( ); i++ )
{
for( int j = 0; j < game.getSide( ); j++ )
{
if ( ae.getSource( ) == squares[i][j] )
{
if ( game.tryToPlay( i, j ) )
update( i, j );
return;
} // end if
} // end inner for loop
} // outer for loop
} // end actionPerformed method
} // end ButtonHandler class
} // end Game class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NestedLayoutPractice extends JFrame
{
private Container contents;
private Game game;
private BorderLayout bl;
private JLabel bottom;
// ***** Task 1: declare a JPanel named top
// also declare three JButton instance variables
// that will be added to the JPanel top
// these buttons will determine the grid size of the game:
// 3-by-3, 4-by-4, or 5-by-5
// Part 1 student code starts here:
// Part 1 student code ends here.
public NestedLayoutPractice()
{
super(\"Practicing layout managers\");
contents = getContentPane();
// ***** Task 2:
// instantiate the BorderLayout manager bl
// Part 2 student code starts here:
// set the layout manager of the content pane contents to bl:
game = new Game(3); // instantiating the GamePanel object
// add panel (game) to the center of the content pane
// Part 2 student code ends here.
bottom = new JLabel(.
In Java Write a GUI application to simulate writing out a check. The.pdfflashfashioncasualwe
In Java Write a GUI application to simulate writing out a check. The value of a check can be
between 0 – 999,999,999,999.99. Your application will accept a name and a value. And display
it on a check. As a minimum you will display the following information: Bank name Pay to the
order of Amount in words Comma separate amount. Your GUI does not have to be exactly as
shown but must have the information indicated above.
Solution
Class cheque is used to enter values
public class Cheque extends javax.swing.JFrame {
public Cheque() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings(\"unchecked\")
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText(\"Name\");
jLabel2.setText(\"Amount\");
jButton1.setText(\"Submit\");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel3.setText(\"Enter Values\");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(12, 12, 12)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton1)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(jTextField2,
javax.swing.GroupLayout.PREFERRED_SIZE, 240,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE,
45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField1,
javax.swing.GroupLayout.PREFERRED_SIZE, 240,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE,
206, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(32, 32, 32)))
.addContainerGap(7, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 34,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addCo.
Listings for BinaryHeap.java and BinaryHeapTest.java are shown in th.pdfRAJATCHUGH12
Listings for BinaryHeap.java and BinaryHeapTest.java are shown in the menu at left
Everything in the BinaryHeap class has been written except the add and remove methods, which
you must write:
First, implement add, then run the test class and observe the testAdd results
Next, implement remove, then run the test class and observe the testRemove results
testAdd and testRemove should both run without errors
Note:
A comp object implementing the Comparator interface is passed to the binary heap\'s
constructor. You will need to use the comp object\'s compare method when making comparisons
in the add and remove operations.
The parent, leftChild, and rightChild methods in BinaryHeapTest are for testing purposes only,
and should not be used to implement add and remove
Solution
BinaryHeapTest.java
import java.util.Comparator;
import org.junit.Test;
import static org.junit.Assert.*;
public class BinaryHeapTest {
/**
* A binary heap of Integer objects
*/
private BinaryHeap bh;
/**
* Some Integer nodes for testing
*/
private Integer n1, n2, n3, n4, n5, n6, n7, n8, n9, n10;
/**
* An object for comparing Integer nodes
*/
private Comparator comp;
public BinaryHeapTest() {
comp = new Comparator() {
public int compare(Integer t, Integer t1) {
return t.compareTo(t1);
}
};
bh = new BinaryHeap(10, comp);
n1 = new Integer(1);
n2 = new Integer(2);
n3 = new Integer(3);
n4 = new Integer(4);
n5 = new Integer(5);
n6 = new Integer(6);
n7 = new Integer(7);
n8 = new Integer(8);
n9 = new Integer(9);
n10 = new Integer(10);
}
@Test
public void testAdd() {
buildHeap();
assertTrue(leftChild(n1) == n2);
assertTrue(rightChild(n1) == n5);
assertTrue(leftChild(n2) == n4);
assertTrue(rightChild(n2) == n3);
assertTrue(leftChild(n5) == n9);
assertTrue(rightChild(n5) == n6);
assertTrue(leftChild(n4) == n10);
assertTrue(rightChild(n4) == n7);
assertTrue(leftChild(n3) == n8);
assertTrue(rightChild(n3) == null);
assertTrue(leftChild(n9) == null);
assertTrue(rightChild(n9) == null);
assertTrue(leftChild(n6) == null);
assertTrue(rightChild(n6) == null);
assertTrue(parent(n10) == n4);
assertTrue(parent(n7) == n4);
assertTrue(parent(n8) == n3);
assertTrue(parent(n4) == n2);
assertTrue(parent(n3) == n2);
assertTrue(parent(n9) == n5);
assertTrue(parent(n6) == n5);
assertTrue(parent(n2) == n1);
assertTrue(parent(n5) == n1);
assertTrue(parent(n1) == null);
}
/**
* An auxiliary method that builds a heap that should look like:
*
* 1
* / \\
* 2 5
* / \\ / \\
* 4 3 9 6
* / \\ /
* 10 7 8
*/
private void buildHeap() {
bh.clear();
assertTrue(bh.isEmpty());
bh.add(n10);
bh.add(n9);
bh.add(n8);
bh.add(n7);
bh.add(n6);
bh.add(n5);
bh.add(n4);
bh.add(n3);
bh.add(n2);
bh.add(n1);
assertTrue(bh.size() == 10);
}
@Test
public void testRemove() {
buildHeap();
assertTrue(bh.remove() == n1);
assertTrue(bh.remove() == n2);
assertTrue(bh.remove() == n3);
assertTrue(bh.remove() == n4);
assertTrue(bh.remove() == n5);
assertTrue(bh.remove() == n6);
assertTrue(bh.remove() == n7);
assertTrue(bh.remove() == n8);
assertTru.
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdfudit652068
Working with Layout Managers. Notes: 1. In part 2, note that the Game class inherits from
JPanel. Therefore, the panel you are asked to add to the center of the content pane is the \"game\"
object. 2. In part 4, at the end of the function, call validate(). This is not mentioned in the book,
but it is mentioned in the framework comments.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Game extends JPanel
{
private JButton [][] squares;
private TilePuzzle game;
public Game( int newSide )
{
game = new TilePuzzle( newSide );
setUpGameGUI( );
}
public void setUpGame( int newSide )
{
game.setUpGame( newSide );
setUpGameGUI( );
}
public void setUpGameGUI( )
{
removeAll( ); // remove all components
setLayout( new GridLayout( game.getSide( ),
game.getSide( ) ) );
squares = new JButton[game.getSide( )][game.getSide( )];
ButtonHandler bh = new ButtonHandler( );
// for each button: generate button label,
// instantiate button, add to container,
// and register listener
for ( int i = 0; i < game.getSide( ); i++ )
{
for ( int j = 0; j < game.getSide( ); j++ )
{
squares[i][j] = new JButton( game.getTiles( )[i][j] );
add( squares[i][j] );
squares[i][j].addActionListener( bh );
}
}
setSize( 300, 300 );
setVisible( true );
}
private void update( int row, int col )
{
for ( int i = 0; i < game.getSide( ); i++ )
{
for ( int j = 0; j < game.getSide( ); j++ )
{
squares[i][j].setText( game.getTiles( )[i][j] );
}
}
if ( game.won( ) )
{
JOptionPane.showMessageDialog( Game.this,
\"Congratulations! You won!\ Setting up new game\" );
// int sideOfPuzzle = 3 + (int) ( 4 * Math.random( ) );
// setUpGameGUI( );
}
}
private class ButtonHandler implements ActionListener
{
public void actionPerformed( ActionEvent ae )
{
for( int i = 0; i < game.getSide( ); i++ )
{
for( int j = 0; j < game.getSide( ); j++ )
{
if ( ae.getSource( ) == squares[i][j] )
{
if ( game.tryToPlay( i, j ) )
update( i, j );
return;
} // end if
} // end inner for loop
} // outer for loop
} // end actionPerformed method
} // end ButtonHandler class
} // end Game class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NestedLayoutPractice extends JFrame
{
private Container contents;
private Game game;
private BorderLayout bl;
private JLabel bottom;
// ***** Task 1: declare a JPanel named top
// also declare three JButton instance variables
// that will be added to the JPanel top
// these buttons will determine the grid size of the game:
// 3-by-3, 4-by-4, or 5-by-5
// Part 1 student code starts here:
// Part 1 student code ends here.
public NestedLayoutPractice()
{
super(\"Practicing layout managers\");
contents = getContentPane();
// ***** Task 2:
// instantiate the BorderLayout manager bl
// Part 2 student code starts here:
// set the layout manager of the content pane contents to bl:
game = new Game(3); // instantiating the GamePanel object
// add panel (game) to the center of the content pane
// Part 2 student code ends here.
bottom = new JLabel(.
In Java Write a GUI application to simulate writing out a check. The.pdfflashfashioncasualwe
In Java Write a GUI application to simulate writing out a check. The value of a check can be
between 0 – 999,999,999,999.99. Your application will accept a name and a value. And display
it on a check. As a minimum you will display the following information: Bank name Pay to the
order of Amount in words Comma separate amount. Your GUI does not have to be exactly as
shown but must have the information indicated above.
Solution
Class cheque is used to enter values
public class Cheque extends javax.swing.JFrame {
public Cheque() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings(\"unchecked\")
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText(\"Name\");
jLabel2.setText(\"Amount\");
jButton1.setText(\"Submit\");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel3.setText(\"Enter Values\");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(12, 12, 12)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton1)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(jTextField2,
javax.swing.GroupLayout.PREFERRED_SIZE, 240,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE,
45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField1,
javax.swing.GroupLayout.PREFERRED_SIZE, 240,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE,
206, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(32, 32, 32)))
.addContainerGap(7, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 34,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addCo.
Listings for BinaryHeap.java and BinaryHeapTest.java are shown in th.pdfRAJATCHUGH12
Listings for BinaryHeap.java and BinaryHeapTest.java are shown in the menu at left
Everything in the BinaryHeap class has been written except the add and remove methods, which
you must write:
First, implement add, then run the test class and observe the testAdd results
Next, implement remove, then run the test class and observe the testRemove results
testAdd and testRemove should both run without errors
Note:
A comp object implementing the Comparator interface is passed to the binary heap\'s
constructor. You will need to use the comp object\'s compare method when making comparisons
in the add and remove operations.
The parent, leftChild, and rightChild methods in BinaryHeapTest are for testing purposes only,
and should not be used to implement add and remove
Solution
BinaryHeapTest.java
import java.util.Comparator;
import org.junit.Test;
import static org.junit.Assert.*;
public class BinaryHeapTest {
/**
* A binary heap of Integer objects
*/
private BinaryHeap bh;
/**
* Some Integer nodes for testing
*/
private Integer n1, n2, n3, n4, n5, n6, n7, n8, n9, n10;
/**
* An object for comparing Integer nodes
*/
private Comparator comp;
public BinaryHeapTest() {
comp = new Comparator() {
public int compare(Integer t, Integer t1) {
return t.compareTo(t1);
}
};
bh = new BinaryHeap(10, comp);
n1 = new Integer(1);
n2 = new Integer(2);
n3 = new Integer(3);
n4 = new Integer(4);
n5 = new Integer(5);
n6 = new Integer(6);
n7 = new Integer(7);
n8 = new Integer(8);
n9 = new Integer(9);
n10 = new Integer(10);
}
@Test
public void testAdd() {
buildHeap();
assertTrue(leftChild(n1) == n2);
assertTrue(rightChild(n1) == n5);
assertTrue(leftChild(n2) == n4);
assertTrue(rightChild(n2) == n3);
assertTrue(leftChild(n5) == n9);
assertTrue(rightChild(n5) == n6);
assertTrue(leftChild(n4) == n10);
assertTrue(rightChild(n4) == n7);
assertTrue(leftChild(n3) == n8);
assertTrue(rightChild(n3) == null);
assertTrue(leftChild(n9) == null);
assertTrue(rightChild(n9) == null);
assertTrue(leftChild(n6) == null);
assertTrue(rightChild(n6) == null);
assertTrue(parent(n10) == n4);
assertTrue(parent(n7) == n4);
assertTrue(parent(n8) == n3);
assertTrue(parent(n4) == n2);
assertTrue(parent(n3) == n2);
assertTrue(parent(n9) == n5);
assertTrue(parent(n6) == n5);
assertTrue(parent(n2) == n1);
assertTrue(parent(n5) == n1);
assertTrue(parent(n1) == null);
}
/**
* An auxiliary method that builds a heap that should look like:
*
* 1
* / \\
* 2 5
* / \\ / \\
* 4 3 9 6
* / \\ /
* 10 7 8
*/
private void buildHeap() {
bh.clear();
assertTrue(bh.isEmpty());
bh.add(n10);
bh.add(n9);
bh.add(n8);
bh.add(n7);
bh.add(n6);
bh.add(n5);
bh.add(n4);
bh.add(n3);
bh.add(n2);
bh.add(n1);
assertTrue(bh.size() == 10);
}
@Test
public void testRemove() {
buildHeap();
assertTrue(bh.remove() == n1);
assertTrue(bh.remove() == n2);
assertTrue(bh.remove() == n3);
assertTrue(bh.remove() == n4);
assertTrue(bh.remove() == n5);
assertTrue(bh.remove() == n6);
assertTrue(bh.remove() == n7);
assertTrue(bh.remove() == n8);
assertTru.
Please help with this. program must be written in C# .. All of the g.pdfmanjan6
Please help with this. program must be written in C# .. All of the game logic must be written in a
seperate class using using an array that is passed in through a prperty that represents the game
board. The class needs to have methods to determine of someone won, or if there was a tie,
make sure all business logic is in a seperate class anot behind the UI..
***** These are the complete in instructions for the game assignment design
Create a Tic-Tac-Toe game that can be played by two players. The form will consist of a Tic-
Tac-Toe board in which the users’ click on to choose their space. As the game is being played
the Game Status section will tell whose turn it is. When someone wins or there is a tie, a message
will be displayed in the Game status section telling the users the status. When someone wins the
game the winning move needs to be indicated. There also needs to be a section that keeps track
of the number of wins for each player, and the number of ties. When the game is finished the
user may click the “Start Game” button to start a new game.
This program will consist of the main form and at least one class that will define the rules of the
game. This class will have an array that is passed in through a property that represents the game
board. The class will then have methods within it that determines if someone won, if there is a
tie, or if neither has occurred yet. Make sure all business logic is in a separate class and not
behind the UI.
EXTRA CREDIT (10 Points)
Create a computer player that can be played against. The computer player will need to be smart
enough to make a winning move or to block a winning move.
Solution
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace Tic_Tac_Toe
{
///
/// Description of MainForm.
///
public partial class MainForm : Form
{
Logic logicObj = new Logic();
public MainForm()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
//
// TODO: Add constructor code after the InitializeComponent() call.
//
}
int turn=1;
int click1=0,click2=0,click3=0,click4=0,click5=0,click6=0,click7=0,click8=0,click9=0;
int player1=0,player2=0;
void Button1Click(object sender, EventArgs e)
{
if(click1==0)
{
if(turn%2!=0)
{
button1.Text=\"X\";
click1++;
}
else
{
button1.Text=\"O\";
click1++;
}
turn++;
}
else
{
button1.Text=button1.Text;
}
display();
int a = logicObj.winLossFunc(button1.Text, button2.Text, button3.Text, button4.Text,
button5.Text, button6.Text, button7.Text, button8.Text, button9.Text);
if (a==1)
{
player1++;
player1score.Text = player1.ToString();
cleargame();
}
else if(a==2)
{
player2++;
player2score.Text = player2.ToString();
cleargame();
}
}
void Button2Click(object sender, EventArgs e)
{
if(click2==0)
{
if(turn%2!=0)
{
button2.Text=\"X\";
click2++;
}
else
{
button2.Text=\"O\";
click2++;
}
turn++;
}
else
{
button2.Text=button2.Text;
}
display();
int a = logicObj.winLossFunc(button1.Text, b.
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...Haris Mahmood
As front-end developers become more and more capable of building web applications, the value of testing front-end code is now more valuable than ever. Unfortunately, the testing ecosystem can be confusing, and daunting to those just getting started with the vast number of libraries and testing frameworks offering various tools and capabilities.
This talk aims to navigate the world of testing front-end code, and provide steps for front-end developers to incorporate testing into their work and projects quickly and with ease!
An Introduction to the World of Testing for Front-End DevelopersFITC
Presented at Web Unleashed 2017. More info at www.fitc.ca/webu
Presented by Haris Mahmood, Shopify
Overview
As front-end developers become more and more capable of building web applications, the value of testing front-end code is now more valuable than ever. Unfortunately, the testing ecosystem can be confusing, and daunting to those just getting started with the vast number of libraries and testing frameworks offering various tools and capabilities.
This talk aims to navigate the world of testing front-end code, and provide steps for front-end developers to incorporate testing into their work and projects quickly and with ease!
Objective
Provide an introduction and overview of the world of testing for front-end development, and tips and steps to get started today.
Target Audience
Front-end developers with no or little experience with testing.
Five Things Audience Members Will Learn
Understanding on why testing is important
What options exist for testing today
What type of tests are best for what scenario
How to assess what frameworks and libraries to use
Steps on getting started with testing
Write a program that mimics the operations of several vending machin.pdfeyebolloptics
Write a program that mimics the operations of several vending machines. More specifically, the
program simulates what happens when the user chooses one of the vending machines, inputs
money and picks an item from the vending machine. Assume there are two vending machines:
one for drinks and one for snacks. Each vending machine contains several items. The name,
price, and quantity of each item is given in two text files; one named “drinks.txt” for the drinks
vending machine and the other named “snacks.txt” for the snacks vending machine.
The format of the input values is comma-separated. The items listed should be organized in the
file with the following order: name, price, quantity. Here are some example items:
The actual reading and parsing of the input file is already handled in the class supplied to you
(see code on BlackBoard). You are given the variables as individual values. You will need to
create the .txt files for creating and testing your vending machines.
You will need to create/complete three classes for this homework assignment: Item,
VendingMachine, and VendingMachineDriver.
Problem Description
Milk,2.00,1
Within your VendingMachine class, include these methods:
VendingMachineThisconstructormethodwilltakeinthenameoftheinputfileand create a vending
machine object. A vending machine object will contain an array of Item objects called stock and
an amount of revenue earned. This constructor method has been completed for you and should
work appropriately once you have completed the rest of this class and the other class definitions.
vendThismethodwillsimulatethevendingtransactionafteravalidamountofmoney and an item
selection are entered. This method will decide if the transaction is successful (enough money or
item) and update the vending machine appropriately.
outputMessage This method will print an appropriate message depending on the success of the
transaction. If the user does not have enough money to buy the chosen item, the vending machine
should prompt the user to enter more money or exit the machine. If the vending machine is out of
the chosen item, the program will print an apology message and prompt the user to choose
another item or exit the machine. If there is enough money for the item selected, then the
vending machine will give the user the item and return the change.
printMenuThismethodprintsthemenuofitemsforthechosenvendingmachine. The Item class needs
to include the following data variables:
• description as a String
• price as a double
• quantity as an int
Within your VendingMachineDriver class, include a main method as the starting point for your
solution that creates the vending machine objects appropriately and then use a loop that
continues interacting with the vending machines until the user enters “X” to exit. See the sample
session for details.
As you implement your solution, you might find that some methods contain some repeated
coding logic. To avoid unnecessary redundancies in your code, have these method.
Complete the classes shown below 1. The MinHeap Class Write necessa.pdfamericanopticalscbe
Complete the classes shown below: 1. The MinHeap Class Write necessary code in the method
buildMinHeap, downHeap and upHeap. Add your necessary changes in the section where this
block of code is written: /*** *** Write YOUR CODE HERE *** ***/ The driver generates a
Sorted List of decreasing order using HeapSort after the specified heap operations are performed.
The details of these methods are given below, also additional hints are provided in the code as
comments. Also we have added helper methods for generating output. Do not edit any helper
methods, they are necessary for Gradescope. Complete the code before the due date. Submit the
completed MinHeap.java file via Gradescope module in folio. Details of Methods:
buildMinHeap: Given an array of N elements, stored from indices 1 thru N, build a min-heap
using bottom-up construction. The helper functions in the DriverPA2.java file read the size and
populate the input array before calling on your buildMinHeap operation. downHeap: downHeap
is an operation that is used to maintain the heap property after removing the root node from a
heap. When the root node is removed, the last node in the heap is moved to the root position, and
the downHeap operation is applied to this node to restore the heap property During downHeap,
the node is compared with its children, and if its value is greater than the value of its children , it
is swapped with the child that has the lowest value. This process is repeated until the heap
property is restored. downHeap will restore the heap-order property by swapping key k along a
downward path from the root. You need to maintain the Min Heap properties within the reduced
size of the array. upHeap: upHeap is an operation that is used to maintain the heap property after
inserting a new node into the heap. When a new node is inserted, it is placed at the bottom of the
heap and the upHeap operation is applied to this node to restore the heap property. During
upHeap, the node is compared with its parent, and if its value is less than the value of its parent ,
it is swapped with its parent. This process is repeated until the heap property is restored. upHeap
will restore the heap-order property by swapping k along an upward path from the insertion
node. During each insertion process, you need to ensure the MinHeap property is maintained.
Input File Structure: Example: minheap0.txt 7 // Input array size(size_n) 21 16 13 12 9 7 3 //
Input Array for MinHeap build (int[] minHeap) 10 30 20 5 15 // Integer array to be inserted in
the MinHeap(int[] newelements) Sample Output in DriverPA2: Result after buildheap: 3 9 7 12
16 21 13 Removed Elements: 3 7 9 12 13 HeapSort result: 30 21 20 16 15 10 5 We have added 5
more input files, you can test them as well changing the file name in the Driver.java main
method. These are the files: minheap1.txt minheap2.txt minheap3.txt minheap4.txt minheap5.txt
Additional Notes: We have allocated the size of the Input Array more than enough capacity f.
Please help!!I wanted to know how to add a high score to this prog.pdfJUSTSTYLISH3B2MOHALI
Please help!!
I wanted to know how to add a high score to this program and wanted to add how many times
you press the spacebar
import javax.swing.*;
import java.awt.*;
/**
* Created by Thomas on 11/27/2016.
*/
public class Renderer extends JPanel{
//private static final long serialVersionUID = 1L;
protected void paintComponent(Graphics g) {
Main.main.repaint(g);
}
public static int clamp(int greenValue, int i, int j) {
// TODO Auto-generated method stub
return 0;
}
}
OTHER PART:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.*;
/**
* Created by Thomas on 11/27/2016.
*/
public class Main implements ActionListener, KeyListener{
public static Main main;
public final int WIDTH = 1400;
public final int HEIGHT = 600;
public HUD Hud;
public Renderer renderer;
public Rectangle character;
public ArrayList cloud;
public Random rand;
public boolean start = false, gameover = false;
public int tick;
public Main() {
JFrame jFrame = new JFrame();
Timer timer = new Timer(20, this);
renderer = new Renderer();
rand = new Random();
jFrame.setTitle(\"Example\");
jFrame.add(renderer);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setSize(WIDTH, HEIGHT);
jFrame.addKeyListener(this);
jFrame.setVisible(true);
cloud = new ArrayList();
character = new Rectangle(200, 220, 20, 20);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
timer.start();
}
public void repaint(Graphics g) {
g.setColor(Color.black);
g.fillRect(0,0, WIDTH, HEIGHT);
g.setColor(Color.blue);
g.fillRect(0, HEIGHT - 100, WIDTH, 100);
g.setColor(Color.green);
g.fillRect(character.x, character.y, character.width, character.height);
if (character.y >= HEIGHT - 100 || character.y < 0) {
gameover = true;
}
for (Rectangle rect : cloud) {
g.setColor(Color.white);
g.fillRect(rect.x, rect.y, rect.width, rect.height);
}
g.setColor(Color.WHITE);
g.setFont(new Font(\"Times New Roman\", 1 ,100));
if (!start) {
g.drawString(\"Press to start!\", 450, HEIGHT / 2);
}
else if (gameover) {
g.drawString(\"Game Over!\", 450, HEIGHT / 2);
}
}
public void addCloud(boolean start) {
int width = 400;
int height = 200;
if (start) {
cloud.add(new Rectangle(WIDTH + width + cloud.size() * 300, rand.nextInt(HEIGHT-120),
80, 100));
}
else {
cloud.add(new Rectangle(cloud.get(cloud.size() - 1).x + 300, rand.nextInt(HEIGHT-120), 80,
100));
}
}
public void flap() {
if (gameover) {
character = new Rectangle(300, 400, 40, 40);
cloud.clear();
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
gameover = false;
}
if (!start) {
start = true;
}
else if (!gameover) {
character.y -= 70;
tick = 0;
}
}
@Override
public void actionPerformed(ActionEvent e) {
int speed = 15;
//System.out.println(\"Space.
I dont know what is wrong with this roulette program I cant seem.pdfarchanaemporium
I don\'t know what is wrong with this roulette program I can\'t seem to get it to run.
Game Class:
public class Game {
public static void main(String[] args) {
Table table = new Table();
BinBuilder bb = new BinBuilder();
Outcome black = new Outcome(\"Black\", 35);
Bet bet = new Bet(10, black);
table.placeBet(bet);
Bin bin = bb.wheel.get(8);
System.out.println(bin.toString());
System.out.println(table.bets.toString());
System.out.println(black.toString());
ListIterator i = table.bets.listIterator();
Iterator b = bin.outcomes.iterator();
while(i.hasNext()) {
System.out.println(i.next().outcome.name.toString());
while(b.hasNext()){
System.out.println(b.next().name.toString());
if(i.next().outcome.equals(b.next())){
System.out.println(\"Win!\");
}
else{
System.out.println(\"Win :/\");
}
}
}
}
}
Player Class
public class Player {
public Table table;
public Outcome black;
public Bet bet;
public Player(Table table) {
table = new Table();
black = new Outcome(\"Black\", 1);
}
void placeBets() {
Bet bet = new Bet(100, black);
table.placeBet(bet);
}
void win(Bet bet) {
System.out.println(\"You\'ve won: \" + bet.winAmount());
}
void lose(Bet bet) {
System.out.println(\"You lost!\" + bet.loseAmount() + \":/\");
}
}
Outcome class
public class Outcome implements Comparable {
public String name;
public int odds;
public Outcome(String name, int odds){
this.name = name;
this.odds = odds;
}
public int winAmount(int amount){
return amount*this.odds;
}
public boolean equals(Outcome other){
return (this.name.equals(other.name));
}
public String toString() {
Object[] values= { name, new Integer(odds) };
String msgTempl= \"{0} ({1}:1)\";
return MessageFormat.format( msgTempl, values );
}
@Override
public int compareTo(E arg0) {
if(this.equals(arg0)){
return 0;
}
return 1;
}
}
Table Class
public class Table {
public int limit = 1000;
public LinkedList bets;
public Table() {
bets = new LinkedList();
}
public boolean isValid(Bet bet) {
int sum = 0;
for(Bet bett: bets) {
sum += bett.amountBet;
}
return (sum>limit);
}
public void placeBet(Bet bet) {
bets.add(bet);
}
ListIterator iterator() {
return bets.listIterator();
}
}
Wheel Class
public class Wheel extends TreeSet {
Vector bins;
NonRandom rng;
Set all_outcomes;
Wheel(NonRandom rng){
this.rng = rng;
rng = new NonRandom();
all_outcomes = new TreeSet();
bins = new Vector(38);
for (int i=0; i<38; i++){
bins.add(i, new Bin());
}
}
Bin next(){
int rand = rng.next(38);
return bins.elementAt(rand);
}
Bin get(int bin){
return bins.elementAt(bin);
}
public Outcome getOutcome( String name ){
TreeSet result= new TreeSet();
for( Iterator i = all_outcomes.iterator(); i.hasNext(); ) {
Outcome oc= i.next();
if( oc.name.contains(name) ) {result.add( oc );}
}
return result.first();
}
public void addOutcome(int bin, Outcome outcome) {
all_outcomes.add(outcome);
this.bins.elementAt(bin).add(outcome);
}
}
Bet Class
public class Bet {
public int amountBet;
public Outcome outcome;
public Bet(int amount, Outcome outcome) {
this.outcome = o.
JavaScript Objects and OOP Programming with JavaScriptLaurence Svekis ✔
Get this Course
https://www.udemy.com/javascript-objects-oop/?couponCode=SLIDESHARE
Use objects to create amazing things with JavaScript power up your applications OOP JavaScript coding
Hello. I need help fixing this Java Code on Eclipse. Please fix part.pdfflashfashioncasualwe
Hello. I need help fixing this Java Code on Eclipse. Please fix parts indicated as \"//Fix\" or
\"//Fill-in\". The code given is the first image. Thank you! Sample outputs are given below along
with what the code is required to do. import java til. Random import java til. Scanner public class
GenCheeseShopv2 public static void intro (Stringt] names, double []prices int amounts Fill-in
public static void getAmount (Scanner input, String[] names, int[] amounts) public static void
itemizedList (String[] names, double Prices int[] amounts) Fill-i public static double
calcSubTotal (double prices, int amounts return 0; pub. lic static int discount (double subTotal
return 0; pub. lic static oid print Total (double subTotal int discount) Fill-in public static void mi
args final int MAXCH EESEE DO NOT CHANGE ANYTHING BELOW String[] names new
String CMAXCH EESE double[] prices new double EESE] int[] amounts new int
[MAXCHEESEJ Scanner input new Scanner (Syste intro names, prices, amounts get Amo unt
input, names, amounts double total calcSubTotal (prices, amounts if EESEE 0) System. out print
Display the itemized list? (1 for yes) int itemized input-nex if item 1) itemized List (names,
prices, amounts); System. out. println(); print Total(total, discount total));
Solution
import java.util.Random;
import java.util.Scanner;
public class GenCheeseShopv2 {
public static void intro(String[] names, double[] prices,int[] amounts){
System.out.println(\"We sell \"+names.length+\" kinds of cheese\");
for(int i=0;i0)
System.out.println(amounts[i]+\" lbs of \"+names[i]+\" @ \"+prices[i]+\" =
$\"+(amounts[i]*prices[i]));
}
}
public static double calcSubTotal( double[] prices,int[] amounts){
double subTotal=0;
for(int i=0;i100)
return 10;
else if(subTotal > 50)
return 25;
else
return 0;
}
public static void printTotal(double subTotal,int discount){
System.out.println(\"Sub Total : $\"+subTotal);
System.out.println(\"-Discount : $\"+discount);
System.out.println(\"Total : $\"+(subTotal-discount));
}
public static void main(String[] args){
final int MAXCHEESES=4;
String[] names = new String[MAXCHEESES];
double[] prices = new double[MAXCHEESES];
int[] amounts = new int[MAXCHEESES];
Scanner input = new Scanner(System.in);
intro(names, prices, amounts);
getAmount(input, names, amounts);
double total = calcSubTotal(prices, amounts);
if(MAXCHEESES>0){
System.out.println(\"Display the itemized list? (1 for yes)\");
int itemized = input.nextInt();
if(itemized==1){
itemizedList(names, prices, amounts);
}
}
System.out.println();
printTotal(total, discount(total));
}
}.
Write a program in java that asks a user for a file name and prints .pdfatulkapoor33
Write a program in java that asks a user for a file name and prints the number of characters,
words (separated by whitespace), and lines in that file. Then, it replaces each line of the file with
its reverse. For example, if the file contains the following lines (Test1.txt):
This is a test
Hi there
Output on the console:
Number of characters: 22
Number of words: 6
Number of lines: 2
Data written to the file (Test1.txt):
tset a si sihT
ereth iH
Solution
ReadFileCount.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;
public class ReadFileCount {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.println(\"Enter file name: \");
String fileName = scan.next();
StringBuffer finalsb = new StringBuffer();
File file = new File(fileName);
if(file.exists()){
int numberOfLines = 0;
int numberOfCharacters = 0;
int numberOfWords = 0;
Scanner scan1 = new Scanner(file);;
while(scan1.hasNextLine()){
StringBuffer sb = new StringBuffer();
String s = scan1.nextLine();
sb.append(s);
numberOfLines++;
numberOfCharacters = numberOfCharacters + s.length();
String words[] = s.split(\" \");
numberOfWords = numberOfWords + words.length;
finalsb.append(sb.reverse());
finalsb.append(\"\ \");
}
System.out.println(\"Number of characters: \"+numberOfCharacters);
System.out.println(\"Number of words: \"+numberOfWords);
System.out.println(\"Number of lines : \"+numberOfLines);
PrintStream ps =new PrintStream(file);
ps.print(finalsb.toString());
ps.flush();
ps.close();
System.out.println(\"Data written to the file \"+fileName);
}
else{
System.out.println(\"File does not exist\");
}
}
}
Output:
Enter file name:
D:\\\\Test1.txt
Number of characters: 0
Number of words: 0
Number of lines : 0
Data written to the file D:\\\\Test1.txt
Test1.txt
tset a si sihT
ereht iH.
Write a short essay that compares the stories of the birth of Jesus .pdfatulkapoor33
Write a short essay that compares the stories of the birth of Jesus by Matthew and Luke. What
parts of the Gospels point to the divinity of Jesus? How do the stories differ? Read any
footnotes.Be prepared to discuss the differences in how the Gospels begin and the meaning of the
texts.
Solution
Jesus’ birth takes place near the end of the reign of Herod the Great (Matt 2:1; Luke 1:5).
2. The names of the principal characters: Mary, Jesus’ future mother, and Joseph his adopted
father.
3. Mary is a virgin engaged to Joseph but they have not begun to live together nor have they
consummated their marriage (Matt 1:18; Luke 1:27, 34; 2:5).
4. Joseph is of Davidic descent (Matt 1:16-20; Luke 1:27; 2:4).
5. An angel from heaven announces the birth of Jesus (Matt 1:20-21; Luke 1:28-30).
6. Jesus is recognized as a son of David (Matt 1:1; Luke 1:32).
7. Jesus’ conception will take place miraculously i.e. through the Holy Spirit (Matt 1:18, 20;
Luke 1:35).
8. Joseph is not involved in the conception—unlike similar stories in the OT in which it is a
barren woman who conceives though through normal means (Matt 1:18-25; Luke 1:34).
9. The name Jesus is given by the angel prior to his birth (Matt 1:21; Luke 1:31). The Greek for
this in fact is strikingly similar which greatly increases the likelihood to hold on purely historical
critical grounds that this tradition predates both gospels:
10. Jesus is identified as “savior” by the angel (Matt 1:21; Luke 1:31).
11. Jesus is born after Mary and Joseph begin to live together (Matt 1:24-25; Luke 2:4-7).
12. Jesus is born in Bethlehem (Matt 2:1; Luke 2:4-7).
13. The family has a house in Bethlehem (Matt 2:10; Luke 2:7—which I believe refers to
Joseph’s ancestral home in Bethlehem rather than an “inn” or a stable).
14. The family settles in Nazareth sometime after the birth of Jesus (Matt 2:22-23; Luke 2:39,
51).(Matt 1:21): .And she will give birth to a son and you will call his name Jesus.(Luke
1:31): , .And you will give birth to a son and you will call his name Jesus..
More Related Content
Similar to Java ProgrammingImplement an auction application with the followin.pdf
Please help with this. program must be written in C# .. All of the g.pdfmanjan6
Please help with this. program must be written in C# .. All of the game logic must be written in a
seperate class using using an array that is passed in through a prperty that represents the game
board. The class needs to have methods to determine of someone won, or if there was a tie,
make sure all business logic is in a seperate class anot behind the UI..
***** These are the complete in instructions for the game assignment design
Create a Tic-Tac-Toe game that can be played by two players. The form will consist of a Tic-
Tac-Toe board in which the users’ click on to choose their space. As the game is being played
the Game Status section will tell whose turn it is. When someone wins or there is a tie, a message
will be displayed in the Game status section telling the users the status. When someone wins the
game the winning move needs to be indicated. There also needs to be a section that keeps track
of the number of wins for each player, and the number of ties. When the game is finished the
user may click the “Start Game” button to start a new game.
This program will consist of the main form and at least one class that will define the rules of the
game. This class will have an array that is passed in through a property that represents the game
board. The class will then have methods within it that determines if someone won, if there is a
tie, or if neither has occurred yet. Make sure all business logic is in a separate class and not
behind the UI.
EXTRA CREDIT (10 Points)
Create a computer player that can be played against. The computer player will need to be smart
enough to make a winning move or to block a winning move.
Solution
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace Tic_Tac_Toe
{
///
/// Description of MainForm.
///
public partial class MainForm : Form
{
Logic logicObj = new Logic();
public MainForm()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
//
// TODO: Add constructor code after the InitializeComponent() call.
//
}
int turn=1;
int click1=0,click2=0,click3=0,click4=0,click5=0,click6=0,click7=0,click8=0,click9=0;
int player1=0,player2=0;
void Button1Click(object sender, EventArgs e)
{
if(click1==0)
{
if(turn%2!=0)
{
button1.Text=\"X\";
click1++;
}
else
{
button1.Text=\"O\";
click1++;
}
turn++;
}
else
{
button1.Text=button1.Text;
}
display();
int a = logicObj.winLossFunc(button1.Text, button2.Text, button3.Text, button4.Text,
button5.Text, button6.Text, button7.Text, button8.Text, button9.Text);
if (a==1)
{
player1++;
player1score.Text = player1.ToString();
cleargame();
}
else if(a==2)
{
player2++;
player2score.Text = player2.ToString();
cleargame();
}
}
void Button2Click(object sender, EventArgs e)
{
if(click2==0)
{
if(turn%2!=0)
{
button2.Text=\"X\";
click2++;
}
else
{
button2.Text=\"O\";
click2++;
}
turn++;
}
else
{
button2.Text=button2.Text;
}
display();
int a = logicObj.winLossFunc(button1.Text, b.
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...Haris Mahmood
As front-end developers become more and more capable of building web applications, the value of testing front-end code is now more valuable than ever. Unfortunately, the testing ecosystem can be confusing, and daunting to those just getting started with the vast number of libraries and testing frameworks offering various tools and capabilities.
This talk aims to navigate the world of testing front-end code, and provide steps for front-end developers to incorporate testing into their work and projects quickly and with ease!
An Introduction to the World of Testing for Front-End DevelopersFITC
Presented at Web Unleashed 2017. More info at www.fitc.ca/webu
Presented by Haris Mahmood, Shopify
Overview
As front-end developers become more and more capable of building web applications, the value of testing front-end code is now more valuable than ever. Unfortunately, the testing ecosystem can be confusing, and daunting to those just getting started with the vast number of libraries and testing frameworks offering various tools and capabilities.
This talk aims to navigate the world of testing front-end code, and provide steps for front-end developers to incorporate testing into their work and projects quickly and with ease!
Objective
Provide an introduction and overview of the world of testing for front-end development, and tips and steps to get started today.
Target Audience
Front-end developers with no or little experience with testing.
Five Things Audience Members Will Learn
Understanding on why testing is important
What options exist for testing today
What type of tests are best for what scenario
How to assess what frameworks and libraries to use
Steps on getting started with testing
Write a program that mimics the operations of several vending machin.pdfeyebolloptics
Write a program that mimics the operations of several vending machines. More specifically, the
program simulates what happens when the user chooses one of the vending machines, inputs
money and picks an item from the vending machine. Assume there are two vending machines:
one for drinks and one for snacks. Each vending machine contains several items. The name,
price, and quantity of each item is given in two text files; one named “drinks.txt” for the drinks
vending machine and the other named “snacks.txt” for the snacks vending machine.
The format of the input values is comma-separated. The items listed should be organized in the
file with the following order: name, price, quantity. Here are some example items:
The actual reading and parsing of the input file is already handled in the class supplied to you
(see code on BlackBoard). You are given the variables as individual values. You will need to
create the .txt files for creating and testing your vending machines.
You will need to create/complete three classes for this homework assignment: Item,
VendingMachine, and VendingMachineDriver.
Problem Description
Milk,2.00,1
Within your VendingMachine class, include these methods:
VendingMachineThisconstructormethodwilltakeinthenameoftheinputfileand create a vending
machine object. A vending machine object will contain an array of Item objects called stock and
an amount of revenue earned. This constructor method has been completed for you and should
work appropriately once you have completed the rest of this class and the other class definitions.
vendThismethodwillsimulatethevendingtransactionafteravalidamountofmoney and an item
selection are entered. This method will decide if the transaction is successful (enough money or
item) and update the vending machine appropriately.
outputMessage This method will print an appropriate message depending on the success of the
transaction. If the user does not have enough money to buy the chosen item, the vending machine
should prompt the user to enter more money or exit the machine. If the vending machine is out of
the chosen item, the program will print an apology message and prompt the user to choose
another item or exit the machine. If there is enough money for the item selected, then the
vending machine will give the user the item and return the change.
printMenuThismethodprintsthemenuofitemsforthechosenvendingmachine. The Item class needs
to include the following data variables:
• description as a String
• price as a double
• quantity as an int
Within your VendingMachineDriver class, include a main method as the starting point for your
solution that creates the vending machine objects appropriately and then use a loop that
continues interacting with the vending machines until the user enters “X” to exit. See the sample
session for details.
As you implement your solution, you might find that some methods contain some repeated
coding logic. To avoid unnecessary redundancies in your code, have these method.
Complete the classes shown below 1. The MinHeap Class Write necessa.pdfamericanopticalscbe
Complete the classes shown below: 1. The MinHeap Class Write necessary code in the method
buildMinHeap, downHeap and upHeap. Add your necessary changes in the section where this
block of code is written: /*** *** Write YOUR CODE HERE *** ***/ The driver generates a
Sorted List of decreasing order using HeapSort after the specified heap operations are performed.
The details of these methods are given below, also additional hints are provided in the code as
comments. Also we have added helper methods for generating output. Do not edit any helper
methods, they are necessary for Gradescope. Complete the code before the due date. Submit the
completed MinHeap.java file via Gradescope module in folio. Details of Methods:
buildMinHeap: Given an array of N elements, stored from indices 1 thru N, build a min-heap
using bottom-up construction. The helper functions in the DriverPA2.java file read the size and
populate the input array before calling on your buildMinHeap operation. downHeap: downHeap
is an operation that is used to maintain the heap property after removing the root node from a
heap. When the root node is removed, the last node in the heap is moved to the root position, and
the downHeap operation is applied to this node to restore the heap property During downHeap,
the node is compared with its children, and if its value is greater than the value of its children , it
is swapped with the child that has the lowest value. This process is repeated until the heap
property is restored. downHeap will restore the heap-order property by swapping key k along a
downward path from the root. You need to maintain the Min Heap properties within the reduced
size of the array. upHeap: upHeap is an operation that is used to maintain the heap property after
inserting a new node into the heap. When a new node is inserted, it is placed at the bottom of the
heap and the upHeap operation is applied to this node to restore the heap property. During
upHeap, the node is compared with its parent, and if its value is less than the value of its parent ,
it is swapped with its parent. This process is repeated until the heap property is restored. upHeap
will restore the heap-order property by swapping k along an upward path from the insertion
node. During each insertion process, you need to ensure the MinHeap property is maintained.
Input File Structure: Example: minheap0.txt 7 // Input array size(size_n) 21 16 13 12 9 7 3 //
Input Array for MinHeap build (int[] minHeap) 10 30 20 5 15 // Integer array to be inserted in
the MinHeap(int[] newelements) Sample Output in DriverPA2: Result after buildheap: 3 9 7 12
16 21 13 Removed Elements: 3 7 9 12 13 HeapSort result: 30 21 20 16 15 10 5 We have added 5
more input files, you can test them as well changing the file name in the Driver.java main
method. These are the files: minheap1.txt minheap2.txt minheap3.txt minheap4.txt minheap5.txt
Additional Notes: We have allocated the size of the Input Array more than enough capacity f.
Please help!!I wanted to know how to add a high score to this prog.pdfJUSTSTYLISH3B2MOHALI
Please help!!
I wanted to know how to add a high score to this program and wanted to add how many times
you press the spacebar
import javax.swing.*;
import java.awt.*;
/**
* Created by Thomas on 11/27/2016.
*/
public class Renderer extends JPanel{
//private static final long serialVersionUID = 1L;
protected void paintComponent(Graphics g) {
Main.main.repaint(g);
}
public static int clamp(int greenValue, int i, int j) {
// TODO Auto-generated method stub
return 0;
}
}
OTHER PART:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.*;
/**
* Created by Thomas on 11/27/2016.
*/
public class Main implements ActionListener, KeyListener{
public static Main main;
public final int WIDTH = 1400;
public final int HEIGHT = 600;
public HUD Hud;
public Renderer renderer;
public Rectangle character;
public ArrayList cloud;
public Random rand;
public boolean start = false, gameover = false;
public int tick;
public Main() {
JFrame jFrame = new JFrame();
Timer timer = new Timer(20, this);
renderer = new Renderer();
rand = new Random();
jFrame.setTitle(\"Example\");
jFrame.add(renderer);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setSize(WIDTH, HEIGHT);
jFrame.addKeyListener(this);
jFrame.setVisible(true);
cloud = new ArrayList();
character = new Rectangle(200, 220, 20, 20);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
timer.start();
}
public void repaint(Graphics g) {
g.setColor(Color.black);
g.fillRect(0,0, WIDTH, HEIGHT);
g.setColor(Color.blue);
g.fillRect(0, HEIGHT - 100, WIDTH, 100);
g.setColor(Color.green);
g.fillRect(character.x, character.y, character.width, character.height);
if (character.y >= HEIGHT - 100 || character.y < 0) {
gameover = true;
}
for (Rectangle rect : cloud) {
g.setColor(Color.white);
g.fillRect(rect.x, rect.y, rect.width, rect.height);
}
g.setColor(Color.WHITE);
g.setFont(new Font(\"Times New Roman\", 1 ,100));
if (!start) {
g.drawString(\"Press to start!\", 450, HEIGHT / 2);
}
else if (gameover) {
g.drawString(\"Game Over!\", 450, HEIGHT / 2);
}
}
public void addCloud(boolean start) {
int width = 400;
int height = 200;
if (start) {
cloud.add(new Rectangle(WIDTH + width + cloud.size() * 300, rand.nextInt(HEIGHT-120),
80, 100));
}
else {
cloud.add(new Rectangle(cloud.get(cloud.size() - 1).x + 300, rand.nextInt(HEIGHT-120), 80,
100));
}
}
public void flap() {
if (gameover) {
character = new Rectangle(300, 400, 40, 40);
cloud.clear();
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
gameover = false;
}
if (!start) {
start = true;
}
else if (!gameover) {
character.y -= 70;
tick = 0;
}
}
@Override
public void actionPerformed(ActionEvent e) {
int speed = 15;
//System.out.println(\"Space.
I dont know what is wrong with this roulette program I cant seem.pdfarchanaemporium
I don\'t know what is wrong with this roulette program I can\'t seem to get it to run.
Game Class:
public class Game {
public static void main(String[] args) {
Table table = new Table();
BinBuilder bb = new BinBuilder();
Outcome black = new Outcome(\"Black\", 35);
Bet bet = new Bet(10, black);
table.placeBet(bet);
Bin bin = bb.wheel.get(8);
System.out.println(bin.toString());
System.out.println(table.bets.toString());
System.out.println(black.toString());
ListIterator i = table.bets.listIterator();
Iterator b = bin.outcomes.iterator();
while(i.hasNext()) {
System.out.println(i.next().outcome.name.toString());
while(b.hasNext()){
System.out.println(b.next().name.toString());
if(i.next().outcome.equals(b.next())){
System.out.println(\"Win!\");
}
else{
System.out.println(\"Win :/\");
}
}
}
}
}
Player Class
public class Player {
public Table table;
public Outcome black;
public Bet bet;
public Player(Table table) {
table = new Table();
black = new Outcome(\"Black\", 1);
}
void placeBets() {
Bet bet = new Bet(100, black);
table.placeBet(bet);
}
void win(Bet bet) {
System.out.println(\"You\'ve won: \" + bet.winAmount());
}
void lose(Bet bet) {
System.out.println(\"You lost!\" + bet.loseAmount() + \":/\");
}
}
Outcome class
public class Outcome implements Comparable {
public String name;
public int odds;
public Outcome(String name, int odds){
this.name = name;
this.odds = odds;
}
public int winAmount(int amount){
return amount*this.odds;
}
public boolean equals(Outcome other){
return (this.name.equals(other.name));
}
public String toString() {
Object[] values= { name, new Integer(odds) };
String msgTempl= \"{0} ({1}:1)\";
return MessageFormat.format( msgTempl, values );
}
@Override
public int compareTo(E arg0) {
if(this.equals(arg0)){
return 0;
}
return 1;
}
}
Table Class
public class Table {
public int limit = 1000;
public LinkedList bets;
public Table() {
bets = new LinkedList();
}
public boolean isValid(Bet bet) {
int sum = 0;
for(Bet bett: bets) {
sum += bett.amountBet;
}
return (sum>limit);
}
public void placeBet(Bet bet) {
bets.add(bet);
}
ListIterator iterator() {
return bets.listIterator();
}
}
Wheel Class
public class Wheel extends TreeSet {
Vector bins;
NonRandom rng;
Set all_outcomes;
Wheel(NonRandom rng){
this.rng = rng;
rng = new NonRandom();
all_outcomes = new TreeSet();
bins = new Vector(38);
for (int i=0; i<38; i++){
bins.add(i, new Bin());
}
}
Bin next(){
int rand = rng.next(38);
return bins.elementAt(rand);
}
Bin get(int bin){
return bins.elementAt(bin);
}
public Outcome getOutcome( String name ){
TreeSet result= new TreeSet();
for( Iterator i = all_outcomes.iterator(); i.hasNext(); ) {
Outcome oc= i.next();
if( oc.name.contains(name) ) {result.add( oc );}
}
return result.first();
}
public void addOutcome(int bin, Outcome outcome) {
all_outcomes.add(outcome);
this.bins.elementAt(bin).add(outcome);
}
}
Bet Class
public class Bet {
public int amountBet;
public Outcome outcome;
public Bet(int amount, Outcome outcome) {
this.outcome = o.
JavaScript Objects and OOP Programming with JavaScriptLaurence Svekis ✔
Get this Course
https://www.udemy.com/javascript-objects-oop/?couponCode=SLIDESHARE
Use objects to create amazing things with JavaScript power up your applications OOP JavaScript coding
Hello. I need help fixing this Java Code on Eclipse. Please fix part.pdfflashfashioncasualwe
Hello. I need help fixing this Java Code on Eclipse. Please fix parts indicated as \"//Fix\" or
\"//Fill-in\". The code given is the first image. Thank you! Sample outputs are given below along
with what the code is required to do. import java til. Random import java til. Scanner public class
GenCheeseShopv2 public static void intro (Stringt] names, double []prices int amounts Fill-in
public static void getAmount (Scanner input, String[] names, int[] amounts) public static void
itemizedList (String[] names, double Prices int[] amounts) Fill-i public static double
calcSubTotal (double prices, int amounts return 0; pub. lic static int discount (double subTotal
return 0; pub. lic static oid print Total (double subTotal int discount) Fill-in public static void mi
args final int MAXCH EESEE DO NOT CHANGE ANYTHING BELOW String[] names new
String CMAXCH EESE double[] prices new double EESE] int[] amounts new int
[MAXCHEESEJ Scanner input new Scanner (Syste intro names, prices, amounts get Amo unt
input, names, amounts double total calcSubTotal (prices, amounts if EESEE 0) System. out print
Display the itemized list? (1 for yes) int itemized input-nex if item 1) itemized List (names,
prices, amounts); System. out. println(); print Total(total, discount total));
Solution
import java.util.Random;
import java.util.Scanner;
public class GenCheeseShopv2 {
public static void intro(String[] names, double[] prices,int[] amounts){
System.out.println(\"We sell \"+names.length+\" kinds of cheese\");
for(int i=0;i0)
System.out.println(amounts[i]+\" lbs of \"+names[i]+\" @ \"+prices[i]+\" =
$\"+(amounts[i]*prices[i]));
}
}
public static double calcSubTotal( double[] prices,int[] amounts){
double subTotal=0;
for(int i=0;i100)
return 10;
else if(subTotal > 50)
return 25;
else
return 0;
}
public static void printTotal(double subTotal,int discount){
System.out.println(\"Sub Total : $\"+subTotal);
System.out.println(\"-Discount : $\"+discount);
System.out.println(\"Total : $\"+(subTotal-discount));
}
public static void main(String[] args){
final int MAXCHEESES=4;
String[] names = new String[MAXCHEESES];
double[] prices = new double[MAXCHEESES];
int[] amounts = new int[MAXCHEESES];
Scanner input = new Scanner(System.in);
intro(names, prices, amounts);
getAmount(input, names, amounts);
double total = calcSubTotal(prices, amounts);
if(MAXCHEESES>0){
System.out.println(\"Display the itemized list? (1 for yes)\");
int itemized = input.nextInt();
if(itemized==1){
itemizedList(names, prices, amounts);
}
}
System.out.println();
printTotal(total, discount(total));
}
}.
Similar to Java ProgrammingImplement an auction application with the followin.pdf (20)
Write a program in java that asks a user for a file name and prints .pdfatulkapoor33
Write a program in java that asks a user for a file name and prints the number of characters,
words (separated by whitespace), and lines in that file. Then, it replaces each line of the file with
its reverse. For example, if the file contains the following lines (Test1.txt):
This is a test
Hi there
Output on the console:
Number of characters: 22
Number of words: 6
Number of lines: 2
Data written to the file (Test1.txt):
tset a si sihT
ereth iH
Solution
ReadFileCount.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;
public class ReadFileCount {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.println(\"Enter file name: \");
String fileName = scan.next();
StringBuffer finalsb = new StringBuffer();
File file = new File(fileName);
if(file.exists()){
int numberOfLines = 0;
int numberOfCharacters = 0;
int numberOfWords = 0;
Scanner scan1 = new Scanner(file);;
while(scan1.hasNextLine()){
StringBuffer sb = new StringBuffer();
String s = scan1.nextLine();
sb.append(s);
numberOfLines++;
numberOfCharacters = numberOfCharacters + s.length();
String words[] = s.split(\" \");
numberOfWords = numberOfWords + words.length;
finalsb.append(sb.reverse());
finalsb.append(\"\ \");
}
System.out.println(\"Number of characters: \"+numberOfCharacters);
System.out.println(\"Number of words: \"+numberOfWords);
System.out.println(\"Number of lines : \"+numberOfLines);
PrintStream ps =new PrintStream(file);
ps.print(finalsb.toString());
ps.flush();
ps.close();
System.out.println(\"Data written to the file \"+fileName);
}
else{
System.out.println(\"File does not exist\");
}
}
}
Output:
Enter file name:
D:\\\\Test1.txt
Number of characters: 0
Number of words: 0
Number of lines : 0
Data written to the file D:\\\\Test1.txt
Test1.txt
tset a si sihT
ereht iH.
Write a short essay that compares the stories of the birth of Jesus .pdfatulkapoor33
Write a short essay that compares the stories of the birth of Jesus by Matthew and Luke. What
parts of the Gospels point to the divinity of Jesus? How do the stories differ? Read any
footnotes.Be prepared to discuss the differences in how the Gospels begin and the meaning of the
texts.
Solution
Jesus’ birth takes place near the end of the reign of Herod the Great (Matt 2:1; Luke 1:5).
2. The names of the principal characters: Mary, Jesus’ future mother, and Joseph his adopted
father.
3. Mary is a virgin engaged to Joseph but they have not begun to live together nor have they
consummated their marriage (Matt 1:18; Luke 1:27, 34; 2:5).
4. Joseph is of Davidic descent (Matt 1:16-20; Luke 1:27; 2:4).
5. An angel from heaven announces the birth of Jesus (Matt 1:20-21; Luke 1:28-30).
6. Jesus is recognized as a son of David (Matt 1:1; Luke 1:32).
7. Jesus’ conception will take place miraculously i.e. through the Holy Spirit (Matt 1:18, 20;
Luke 1:35).
8. Joseph is not involved in the conception—unlike similar stories in the OT in which it is a
barren woman who conceives though through normal means (Matt 1:18-25; Luke 1:34).
9. The name Jesus is given by the angel prior to his birth (Matt 1:21; Luke 1:31). The Greek for
this in fact is strikingly similar which greatly increases the likelihood to hold on purely historical
critical grounds that this tradition predates both gospels:
10. Jesus is identified as “savior” by the angel (Matt 1:21; Luke 1:31).
11. Jesus is born after Mary and Joseph begin to live together (Matt 1:24-25; Luke 2:4-7).
12. Jesus is born in Bethlehem (Matt 2:1; Luke 2:4-7).
13. The family has a house in Bethlehem (Matt 2:10; Luke 2:7—which I believe refers to
Joseph’s ancestral home in Bethlehem rather than an “inn” or a stable).
14. The family settles in Nazareth sometime after the birth of Jesus (Matt 2:22-23; Luke 2:39,
51).(Matt 1:21): .And she will give birth to a son and you will call his name Jesus.(Luke
1:31): , .And you will give birth to a son and you will call his name Jesus..
Write a 500 word essay on How Emotionally Intelligent am I Using D.pdfatulkapoor33
Write a 500 word essay on: How Emotionally Intelligent am I? Using Daniel Goleman
article\"What makes a leader
Solution
Developing more emotional intelligence (EI) is very important for a successful career. When
individuals have high levels of EI, they build strong effective relationships and manage difficult
situations more successfully. Emotional intelligence is an intelligence having to do with
perceptive and understanding emotional information. Emotional information is in every place.
Emotions speak basic feeling states from one individual to other -- they mention urgent messages
such as \"let\'s get together\".
Psychologist Daniel Goleman fined five elements that make up emotional intelligence. These
are:
Leadership is build through emotional intelligence, which itself can only be achieved through
time, determination, and promise. Without emotional intelligence, leadership is weak,
inaccessible, and remote. True leaders show sympathy, kindness, and behave to their peers and
subordinates alike..
Why is it significant that many antibiotic resistance genes are foun.pdfatulkapoor33
Why is it significant that many antibiotic resistance genes are found on the loops of DNA (mini-
chromosomes) called plasmids?
1. Plasmids can be passed among cells—allowing rapid spread, even between species of bacteria.
2. Antibiotic resistance genes aren’t found on the main bacterial chromosome.
3. Antibiotics and antibiotic resistance genes are produced naturally, often by soil-dwelling
bacteria.
4. Point mutations that confer resistance to a drug can’t occur unless that drug is in the
environment.
Solution
1. Plasmids can be passed among cells—allowing rapid spread, even between species of bacteria.
Plasmids are the extra DNA carried by bacteria; they are transferred to other cells during the
process of conjugation. It is advantageous for the bacteria to carry bacterial resistance genes on
plasmids because they can be transferred from one bacteria to the other and can be transferred
even between species..
Will water molecules in hot water move faster or slower compared to .pdfatulkapoor33
Will water molecules in hot water move faster or slower compared to molecules in cold water?
Will water molecules in water vapor (gas) move slower compared to those in liquid water?
What are some factors that can alter the speed of diffusion?
Solution
a) Water molecules in hot water move faster compared to molecules in cold water.
b) No: In the gas phase—as water vapor—the H2O molecules are farther apart. They move very
fast and spread quickly compared to liquid water.
c) Answer: The factors that affect the rate of diffusion are.
which of the following is true with respect to the 3 classes of chem.pdfatulkapoor33
which of the following is true with respect to the 3 classes of chemical messengers in the body.
a) hormones are released from endocrine cells and travel in the plasma to target cells b)
paracrines are proteins that are released from a secretory cell and travel through the plasma to
neighboring cells c) neurotransmitters are chemical messengers, which are released by the nerve
and bind to receptors on the postsynaptic cell d) both A and C e) all of the above
Solution
Correct answer is : All of the above
There are 3 types of Chemical messengers
1.Paracrines –
• Local chemical messengers
• Exert effect only on neighboring cells in immediate environment of secretion site
2.Neurotransmitters
• Shortrange chemical messengers
• Diffuse across narrow space to act locally on adjoining target cell (another neuron, a muscle, or
a gland)
3.Hormones
• Longrange messengers
• Secreted into blood by endocrine glands in response to appropriate signal
• Exert effect on target cells some distance away from release site
We will see each of this one by one
The human body secretes and circulates some 50 different hormones. A wide variety of these
chemical substances are produced by endocrine cells, most of which are in glands. The hormones
then enter the blood system to circulate throughout the body and activate target cells. The
endocrine system, tightly linked to the nervous system, controls a large number of the body’s
functions: metabolism, homeostasis, growth, sexual activity, and contraction of the smooth and
cardiac muscles.
When a hormone diffuses outside of a capillary, it can act on a target cell – a cell with receptors
that correspond to it. There are two types of hormonal activity. A steroid hormone is capable of
crossing through the cell membrane of the target cell. It unites with a receptor protein located
inside the nucleus, which stimulates or blocks the cell’s genetic activity. A protein hormone, on
the other hand, cannot penetrate the target cell. It attaches to the cell’s membrane and activates a
receptor that releases, in turn, a messenger within the cell.
b) paracrines are proteins that are released from a secretory cell and travel through the plasma to
neighboring cells
In paracrine signaling, the signaling molecules released by a cell only affect target cells in close
proximity to it. The conduction of an electric impulse from one nerve cell to another or from a
nerve cell to a muscle cell (inducing or inhibiting muscle contraction) occurs via paracrine
signaling. The role of this type of signaling, mediated by neurotransmitters, in transmitting nerve
impulses.
Paracrine signaling is a form of cell-to-cell communication in which a cell produces a signal to
induce changes in nearby cells, altering the behavior or differentiation of those cells. Signaling
molecules known as paracrine factors diffuse over a relatively short distance (local action), as
opposed to endocrine factors (hormones which travel considerably longer distances via the
cir.
Which of the following is NOT a difference between the smooth ER and .pdfatulkapoor33
Which of the following is NOT a difference between the smooth ER and the rough ER? The
rough ER has ribosomes; the smooth ER does not. The smooth ER works to detoxify poisons;
the rough ER aren\'t got time for that. The smooth ER creates lipids while the rough ER makes a
lot of membrane proteins. The smooth ER makes phospholipids, but the rough ER does not. The
rough ER makes secretory proteins; the smooth ER does not.
Solution
The smooth ER are engaged in generation of lipids and phospholipids along with detoxification
of poisons from the cells. On the other hand, rough ER are engaged in genertion of proteins since
they carry ribosomes on their surface where translation takes place. Importantly, the rough ER
are involved only in generation of primary sequence of proteins i.e. a polypeptide sequence.
They do not help in folding or generation of secondary structure of proteins. Moreover, the
polypeptide synthesized on rough ER contains a leader seqeunce which helps the nascent
polypeptide to golgi apparatus for transport. This suggests that the rough ER are not involved in
generationof secretory protein.
Thus, this information suggests that choice E is correct..
What sources have helped shape your personal code of ethics and mora.pdfatulkapoor33
What sources have helped shape your personal code of ethics and morality? What influences, if
any, have ever pressured you to compromise those standards? Think of an experience you had at
work or schools that tested your ethical standards. What did you decide to do to resolve your
dilemma? Now that time has passed are you comfortable with the decision you made? If not,
what would you do differently?
Solution
For deciding ethical action there are few standards. Some of them are
1) Rights Approach
Under rights approach, Ethical action that best protects the interests those affects. Every
individual has a right to know truth and he has to considered as an ends not as a means.
2) Utilitarian approach
Ethical action is one which gives greatest good those who affects. Here ends is important means
could be anything
ETHICAL DILEMMA FACED IN SCHOOL
In our school hostel using mobile was illegal, I noticed some of my friends using this. Should I
report this? Is ethical dilemma.
What is a stored function Where is it located How can it be used .pdfatulkapoor33
What is a stored function? Where is it located? How can it be used? Explain
Solution
stored function :-
stored function is nothing but block of code similar to stored procedure which will perform some
operation and returns a single value to the user. stored functions are also called as user defined
functions.
Syntax :-
CREATE OR REPLACE FUNCTION FUNCTION_NAME(PARAMETER DATATYPE)
RETURN(PARAMETER/VARIABLE DATATYPE)
IS/AS
VARIABLE DECLARATION ;
BEGIN
CODE/STATEMENT ;
RETURN(PARAMETER/VARIABLE DATATYPE) ;
END;
/
Example :-
A stored function to return the cube of a given variable value :-
CREATE OR REPLACE FUNCTION F1(X INT)
RETURN INT
IS
BEGIN
RETURN X*X*X ;
END ;
/
Output :-
SELECT F1(5) FROM DUAL ; // Function Call
F1(5)
125..
What are the three fundamental decisions financial managers make and.pdfatulkapoor33
What are the three fundamental decisions financial managers make and identify which part of the
balance sheet each decisions affect.
Solution
1. capital budgeting decisions: Asset side is affected
2. financing decisions: Liabilities side is affected
3. working capital management decisions: Current Assets/Liabilities side is affected.
westphalian order is about what what are the human principle of wes.pdfatulkapoor33
westphalian order is about what? what are the human principle of westphalian? how westphalian
is underpressure of globalization?
Solution
i) Westphalian order: is the principle of international law that each nation state has sovereignty
over its territory and domestic affairs, to the exclusion of all external powers, on the principle of
non-interference in another country\'s domestic affairs, and that each state (no matter how large
or small) is equal in international law. As European influence spread across the globe, the
Westphalian principles, especially the concept of sovereign states, became central to
international law and to the prevailing world order.
ii) Collectively known as the Westphalian system, the principles are:
iii) During the 1980s and early 1990s, the imperative of globalization and interdependence led to
international integration, and the erosion of Westphalian sovereignty. The European Union\'s
concept of shared sovereignty is also somewhat contrary to historical views of Westphalian
sovereignty, as it provides for external agents to influence and interfere in the internal affairs of
its member countries..
Warren Delaney believed that his home was his “castle,” and during t.pdfatulkapoor33
Warren Delaney believed that his home was his “castle,” and during the summer months every
year, his “castle” was a tiny cabin nestled in the woods of upstate New York. Delaney was an
Economics professor at a small college in Florida, and for him, there was no better way to “rest
and recharge” after a hectic academic year than to head north for the cozy confines of his cabin.
For several consecutive years, Warren’s cabin had been vandalized and/or burglarized during
the winter months while he was in Florida. During the winter of 2006, several windows had been
shattered. In the winter of 2007, several pieces of furniture had been stolen. At some point during
the winter of 2008, the bedroom mattress had been ripped apart for some unexplained reason,
with foam and fabric scattered about the bedroom floor. On each of these occasions, the
perpetrator had forced the front door lock open, and had entered the cabin through the front door.
Warren envisioned a way to stop the criminal(s) responsible for these violations. He spring-
loaded a shotgun in the living room of the cabin, and pointed it directly at the front door. The
shotgun was configured so that if someone opened the front door while he was away, it would
fire at the intruder.
Warren returned to his cabin in May 2010 and came upon a grisly scene. The front door had
been opened, and at the threshold was the partially-decomposed body of what appeared to be a
middle-aged man, dead of a shotgun blast to the chest. Warren immediately called the local
sheriff, Officer Brian Mulholland. Upon arriving at the scene and briefly questioning Warren,
Officer Mulholland arrested him.
Was the arrest valid? Did Warren Delaney commit first-degree murder? Did Warren use
justifiable force in this situation?
Solution
Yes, the arrest was valid. This is a case of culpable homicide involving the illegal killing of a
person either with or without an intention to kill.
Here the person has died. The killing was unlawful, wilful and predetermined. It was a planned
murder. So it will be considered a first degree murder.
Justifiable force is use of force in defense, home protection, in defense of property. But the case
is that the force led to the person dying. Warren had planted the gun in such a way that the
intruder will be shot and killed. So the use of force is not justifiable..
Understand 1. Explain the factors that contribute to streamflow befor.pdfatulkapoor33
Understand 1. Explain the factors that contribute to streamflow before, during, and after a storm.
Precipitation overlandStream Stream flow flow flow Baseflow Retun flow Retun flow Baseflow
Solution
Base flow : It is basically contribute to the steam flow after long time of the high precipitation
Return flow: It contribute the steam flow after and during storm to due to topography of the land.
Inter inflow : it is occur just after the storm and contribute to increase base flow and water table.
This phenomenon is primarily responsible for the redistribution of he.pdfatulkapoor33
This phenomenon is primarily responsible for the redistribution of heat across the plant Coriolis
effect curvature of the Earth Adiabatic cooling Biome
Solution
The solar heat gained by our planet from the sun is not even. The uneven heat is redistributed
across the planet by air circulation, water vapour, ocean current, earth rotation. Due to uneven
heat the climate and weather patterns are maintained.
These are the following phenomenon primarily responsible for the redistribution of heat.
Coriolis effect: The Earth rotates once every 24 hours. Due to that rotation, the uneven heat
energy from the sun is redistributed by moving air masses, water vapor and ocean currents. This
effect is called coriolis effect.
Curvature of the earth causes uneven distribution of solar heat. Therefore the solar flux is
maximum at equator than the polars.
Adiabatic cooling is the process of reducing heat through a change in air pressure caused by
volume expansion. In nature when there is very hot, the air close to earth becomes lighten and
moves up and to fullfil that place cold heavy air comes. that results in redistribution of heat
across the earth..
The following questions are about transmissible spongiform encephalop.pdfatulkapoor33
The following questions are about transmissible spongiform encephalopathy (TSE). (0.5 pt.)
TSE\'s are caused by: prions viruses bacteria fungi protozoa helminths
Solution
TSE s, called as Transmissible spongiform encephalopathies.
Also known as Prion diseases.
TSE s are group of progressive conditions ,which effect the brain and nervousystem in many
animals,including humans.
According the most widesprea hypotheis, they are transmited by Prions,
Answer is \"a\"Prions..
Please answer these following questions only if you are sure about t.pdfatulkapoor33
Please answer these following questions only if you are sure about the answer.
Thank you.
Solution
14. B. Choanoflagelleates share common ancestry with animals.
Analysis of the combined data set (concatenated) along with sequences from other closely
related species (animals and fungi) demonstrate that choanoflagellates are strongly supported as
monophyletic and confirm their position as the closest known unicellular living relative of
animals.
15. B. Multicellular haplaid gamete producing organism.
Two single-celled haploid gametes, fuse to form a single-celled diploid zygote. The single-celled
diploid zygote germinates, dividing by the normal process (mitosis),The result is a multi-cellular
diploid organism, called thesporophyte(because at maturity it produces spores).
When it reaches maturity, the sporophyte produces one or moresporangia(singular: sporangium)
which are the organs that produce diploid spore mother cells (sporocytes). These divide by a
special process (meiosis) that reduces the number of chromosomes by a half. This initially results
in four single-celled haploid spores, each containingnunpaired chromosomes. The single-celled
haploid spore germinates, dividing by the normal process (mitosis), which maintains the number
of chromosomes at n. The result is a multi-cellular haploid organism, called
thegametophyte(because it produces gametes at maturity).
16. B. Haploid, gametes.
explanation in the above question..
Multiple choice Which Protozoa phyla is responsible for red tides an.pdfatulkapoor33
Multiple choice: Which Protozoa phyla is responsible for red tides and can be toxic?
Euglenozoa Trypanosomatidea Ciliophora Dinozoa Multiple choice: Which class of Cnidarians
includes corals and anemones? Hydrozoa Scyphozoa Cubozoa Anthozoa Multiple choice:
Adhesive cells in Ctenophores are called: Cnidocysts Nematocystes Nerve net Colloblasts
Solution
Please find the answers below and explanations in parentheses:
Answer 7: Choice 4 (red tide is a phenomenon observed by presence of large amount of algal
blooms in sea with appearance of red coloration of water. These algal blooms are basically
dinoflagellates by nature with colored cell coatings in reddish appearance. Together, these
phytoplanktons give appearance of large red-tides in the sea and are termed as Red tide)
Answer 8: Choice 4 (the class anthozoa of cnidarian organisms include the forms which make up
sedenatry life-style such as corals and sea anemones. They are always sedentary in nature but
produce motile sperms which can perform sexual reproduction. Examples include sea anemone,
Montastraea cavernosa, the corals of the great Australian coral reef etc.)
Answer 9: Choice 4 (Colloblasts are small unique cells distributed in the tentacles of the
ctenophora which help in attaching to the substratum and also help in capturing the prey. They
contain digestive tentacles and sometimes eosinophilic cells inside them which penetrate through
the substrate/prey and help in attaching to them.Thus, colloblasts are the functional cells of
cnidarians for capturing prey).
List the 3 Laws of Robotics and decide which is the most important..pdfatulkapoor33
List the 3 Laws of Robotics and decide which is the most important.
Solution
1) A robot may not injure a human being or, through inaction, allow a human being to come to
harm.
2) A robot must obey the orders given it by human beings except where such orders would
conflict with the First Law.
3) A robot must protect its own existence as long as such protection does not conflict with the
First or Second Laws..
Mainly stuck on why this is not readily available and used in the Un.pdfatulkapoor33
Mainly stuck on why this is not readily available and used in the United States. EcoCute is a
transcritical CO2 heat pump used extensively in Europe and Japan. Investigate this technology
and compare its operational schematic and accompanying T s diagram with that shown in Fig.
10.18. Explore why this technology is not readily available and used within the United States.
Compare its use for a 1000 ft2 dwelling in your locale with a more conventional air-cooled
residential heat pump using a synthetic refrigerant in terms of costs (operational and
environmental impact. What are the impediments to its deployment in the United initial) and
States? Create a PowerPoint presentation of your findings and a supporting project report
Solution
To specifically answer your question, a transcritical CO2 heat pump uses C02 or R744 as the
natural refrigerant which has the following the implications in terms of its behaviour:
1. It combines with water in air to form carbonic acid which has corrosive properties over metal
and can damage limestone and marble.
2.Breathing air that has even ~10% of Co2 content can prove life threatening.
3. R744 is one and a half times heavier than air therefore when released to air, it will accumilate
at low elevations .
As far as its use in the United States is concerned, there are legal liabilities over the long term for
the manufactureres of Co2 heat pumps. Hence it is not readily available as compared to Japan
and Europe..
IP addresses define the a. Application b. The application port .pdfatulkapoor33
IP addresses define the ? a. Application b. The application port c. The network and host/end
system (i.e., computer, mobile device, etc..) d. The network only
Solution
Answer: c
An IP address is a temporary address that is assigned each time a computer or device accesses
the Internet. It serves two principal functions they are host or network interface identification and
locationaddressing..
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxEduSkills OECD
Andreas Schleicher presents at the OECD webinar ‘Digital devices in schools: detrimental distraction or secret to success?’ on 27 May 2024. The presentation was based on findings from PISA 2022 results and the webinar helped launch the PISA in Focus ‘Managing screen time: How to protect and equip students against distraction’ https://www.oecd-ilibrary.org/education/managing-screen-time_7c225af4-en and the OECD Education Policy Perspective ‘Students, digital devices and success’ can be found here - https://oe.cd/il/5yV
We all have good and bad thoughts from time to time and situation to situation. We are bombarded daily with spiraling thoughts(both negative and positive) creating all-consuming feel , making us difficult to manage with associated suffering. Good thoughts are like our Mob Signal (Positive thought) amidst noise(negative thought) in the atmosphere. Negative thoughts like noise outweigh positive thoughts. These thoughts often create unwanted confusion, trouble, stress and frustration in our mind as well as chaos in our physical world. Negative thoughts are also known as “distorted thinking”.
The Indian economy is classified into different sectors to simplify the analysis and understanding of economic activities. For Class 10, it's essential to grasp the sectors of the Indian economy, understand their characteristics, and recognize their importance. This guide will provide detailed notes on the Sectors of the Indian Economy Class 10, using specific long-tail keywords to enhance comprehension.
For more information, visit-www.vavaclasses.com
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
This presentation provides a briefing on how to upload submissions and documents in Google Classroom. It was prepared as part of an orientation for new Sainik School in-service teacher trainees. As a training officer, my goal is to ensure that you are comfortable and proficient with this essential tool for managing assignments and fostering student engagement.
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
The Art Pastor's Guide to Sabbath | Steve ThomasonSteve Thomason
What is the purpose of the Sabbath Law in the Torah. It is interesting to compare how the context of the law shifts from Exodus to Deuteronomy. Who gets to rest, and why?
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
Java ProgrammingImplement an auction application with the followin.pdf
1. Java Programming
Implement an auction application with the following features/functionality:
Inputs for an item and minimum bid amount.
Inputs for bidder name, bid amount and maximum bid. You will implement a class called Bid to
hold this information.
Label controls to show the current high bidder’s name, bid amount and maximum bid. For bid
amounts, you may assume all bids will be a whole dollar value just to simplify things a bit.
A list box to show all entries when the auction is over. You will use the pop() method to retrieve
each bid off the stack and display it. This feature is intended more for test/debug purposes.
You will implement a Stack class that will keep the highest bid at the top of the stack. It must
have the classic stack operations of push() to place an item on the stack, pop() to remove the top
item from the stack, and top() to view the top item on the stack but not remove it. You may use a
linked list of your own design, an array, or the built-in Java Array List or Linked List classes as
the underlying data structure. You may also add an item count property if you want.
The auction will work by the following rules:
When the initial bid is made, it must be greater than or equal to the item’s minimum bid amount
to be placed on the stack.
When another bid is made that is greater than the current high bidder’s maximum bid, that bid
will be pushed to the top of the stack and become the new highest bid.
If another bid is made that is greater than the current high bid but less than or equal to the
current high bidder’s maximum amount, the current high bidder’s bid will be raised to match but
the new bid will not be placed on the stack.
Your application should have a message box or label to indicate the status of the bid operation.
There is no limit on the number of bids.
Solution
// To import features as 'Panel, Button, Label, TextArea, TextField, Color', etc.
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
// In this program, "this." is used instead of "this.getContentPane()." in Auction.init() uses;
class Bidacution
{
2. public static void main (String[] args)
{ Frame gameapp = new Frame ("AUCTION by Henry C. Joy");
gameapp.setSize (750, 560); // larger than actual applet -- allow for edges
gameapp.addWindowListener (new WindowCloser());
Auction display = new Auction();
display.init();
gameapp.add (display);
gameapp.setVisible (true);
}
private static class WindowCloser extends java.awt.event.WindowAdapter
{ public void windowClosing (java.awt.event.WindowEvent e)
{ System.exit (0);
}}
}
// The MAIN method of the software (the init method): using 20 + classes.
public class Auction extends java.applet.Applet // every Applet is a Panel
{
public static final int UNIT = 5; // difference between 2 consec. bids
public static final int BREAK = 5; // separate first 5 from last 4
public static final String REPEAT = "repeat game";
// VIEW objects
private Panel boardPanel = new Panel();
private Panel biddingPanel = new Panel();
private TextArea output = new TextArea (11, 93);
private TextArea area = new TextArea (15, 75);
private TextArea crutch = null; // an option changes this to area
private BidPrompter bidPrompt = new BidPrompter(); // It extends Panel
private Player humanPanel = new Player ("HUMAN");
private Player compyPanel = new Player ("COMPY");
private TwoPlayers twoGuys = new TwoPlayers (humanPanel, compyPanel);
// MODEL objects
private GameStatus status = new GameStatus();
private TotalGames gameCounter = new TotalGames(); // tracks num games
private PropList propList = new PropList(); // tracks 20 properties
public void init() // only on initial setup, not for additional games
{ boardPanel.setLayout (new GridLayout (4, 7, 6, 4));
3. boardPanel.setBackground (Color.white);
addManyComponentsToBiddingPanel();
Panel bottom = new Panel();
bottom.setLayout (new GridLayout (1, 2, 40, 0));
bottom.add (humanPanel);
bottom.add (compyPanel);
this.setLayout (new BorderLayout (2, 2));
this.add (boardPanel, BorderLayout.NORTH);
this.add (biddingPanel, BorderLayout.CENTER);
this.add (bottom, BorderLayout.SOUTH);
startNewGame ("");
}
private void addManyComponentsToBiddingPanel() // only called by init()
{ biddingPanel.setBackground (Color.yellow);
biddingPanel.add (bidPrompt); // using FlowLayout
biddingPanel.add (newButton (" bid ", new MakeBidAl()));
biddingPanel.add (newButton ("pass", new PassBidAL()));
biddingPanel.add (newButton (UNIT +" higher", new HigherAL()));
biddingPanel.add (newButton (UNIT +" lower", new LowerAL()));
biddingPanel.add (newButton ("start new game", new NewGameAL()));
biddingPanel.add (newButton (REPEAT, new NewGameAL()));
biddingPanel.add (newButton ("options", new MoreOptionsAL()));
biddingPanel.add (output);
output.addKeyListener (new Responder());
output.setEditable (false); // I'll echo user's keys myself
output.setBackground (new Color (240, 255, 240)); // pastel green
output.append ("THE AUCTION GAME by Henry C. Joy, Jr. "
+ "Objective: At CASH IN, to have more total value "
+ "(property@$100...$300 plus cash) than compy. "
+ "The hint is the bid that compy thinks the property "
+ "is worth (though bids must be multiples of 5). "
+ "If you pass, compy takes it for the hint, "
+ "rounded down to a multiple of 5 if necessary. "
+ "If you bid what is shown after compy's first bid, "
+ "you get it for that higher bid. "
+ "If you bid what is shown for your first bid, you "
4. + "get it for that or else compy takes it for 5 more; "
+ " if the hint ends in 3,4,8,or 9, raise your bid "
+ "5 higher to be sure to get the property. ");
}
public Button newButton (String label, ActionListener alis)
{ Button but = new Button (label);
but.addActionListener (alis);
return but;
}
/* The CONTROL part of the software -- 11 ActionListeners + Keys on 5 pages */
private class NewGameAL implements ActionListener // click 1 of 2 buttons
{ public void actionPerformed (ActionEvent ev)
{ int numSold = propList.numSold();
if (numSold >= PropList.FIRST_GROUP && numSold < PropList.MAX)
{ int score = twoGuys.score();
int cash = humanPanel.cash() - compyPanel.cash();
if ((score > 60 && cash > 0) || (score < -60 && cash < 0))
output.append (gameCounter.updateTotals (score));
}
boardPanel.removeAll();
humanPanel.removeAll();
compyPanel.removeAll();
startNewGame (((Button) ev.getSource()).getLabel());
}
}
/** startNewGame resets all variables and displays for the start of a
new game. This may occur in the middle of the current game.
Called by init() and also by clicking a NewGameAL button. */
public void startNewGame (String newGame)
{ if ( ! newGame.equals (REPEAT)) // no repeat for first game
{ int id = status.nextGameID();
propList.shuffleToRandomize (id);
newGame = "Game " + id;
}
twoGuys.makeHumanFirst (true);
addPropertiesToTopPanel();
5. int initial = status.getInitialCash();
propList.resetIterator (initial);
humanPanel.addHoldingsToPanel (initial, 0);
compyPanel.addHoldingsToPanel (initial, status.getLoan());
int best = propList.selectBestBid (true, humanPanel.cash(),
compyPanel.cash(), 0, crutch);
bidPrompt.updateForNewBestBid (true, false, false, best);
int val = best * 100 / ((Property) propList.getNext()).getCost();
output.append (" " + newGame + ": The first " + PropList.FIRST_GROUP
+ " properties total $" + propList.getTotalOfFirstGroup()
+ ". Compy bids " + val + " on 100s, " + (2 * val)
+ " on 200s, and " + (3 * val) + " on 300s. ");
biddingPanel.validate(); // re-layout components
}
private void addPropertiesToTopPanel() // only called by startNewGame()
{ propList.resetIterator (0);
boardPanel.add (new Label ("Up for bid ==>"));
for (int k = 0; k < PropList.TOTAL; k++)
boardPanel.add (propList.next());
boardPanel.add (new Label (""));
boardPanel.add (new Label ("")); // so 28 labels = 7 x 4
boardPanel.validate(); // re-layout components
}
private class LowerAL implements ActionListener // click "5 lower"
{ public void actionPerformed (ActionEvent ev)
{ if (bidPrompt.getDisplayedBid() > 0)
bidPrompt.changeDisplayedBid (-UNIT);
}
}
private class HigherAL implements ActionListener // click "5 higher"
{ public void actionPerformed (ActionEvent ev)
{ int bid = bidPrompt.getDisplayedBid();
if (bid <= twoGuys.getFirst().cash()
&& bid < twoGuys.getSecond().cash())
bidPrompt.changeDisplayedBid (UNIT);
}
6. }
private class Responder extends java.awt.event.KeyAdapter
// respond to certain chars typed inside textarea
{ public void keyTyped (java.awt.event.KeyEvent ev)
{ char key = ev.getKeyChar();
if (key == 'b')
new MakeBidAl().actionPerformed (null);
else if (key == 'n')
new PassBidAL().actionPerformed (null);
else if (key == 'm')
{ new HigherAL().actionPerformed (null);
new MakeBidAl().actionPerformed (null);
}
else if (key == 's')
new NewGameAL().actionPerformed
(new ActionEvent (new Button ("start"), 0, null));
else if (key == 'r')
new NewGameAL().actionPerformed
(new ActionEvent (new Button (REPEAT), 0, null));
}
}
private class PassBidAL implements ActionListener // click "pass"
{ public void actionPerformed (ActionEvent ev)
{ if ( ! (propList.getNext() instanceof Property))
return;
twoGuys.makeHumanFirst (true);
output.append (propList.numSold() == BREAK ? ".p" : "p");
compyPanel.makeSale (propList.next(), boardPanel,
twoGuys.bothAreReal() ? bidPrompt.getDisplayedBid()
: bidPrompt.getBestBid() / UNIT * UNIT);
prepareForNextTurn();
}
}
private void prepareForNextTurn() // only called by PassBidAL or MakeBidAl
{ if ( ! (propList.getNext() instanceof Property))
{ ((RentLabel) propList.getNext()).flashIntermittently();
8. if (price >= 0)
compyPanel.makeSale (propList.next(), boardPanel, price);
else
humanPanel.makeSale (propList.next(), boardPanel, bid);
twoGuys.makeHumanFirst (price >= 0);
prepareForNextTurn();
}
}
private class MoreOptionsAL implements ActionListener // click "options"
{ public void actionPerformed (ActionEvent ev)
{ final Frame opt = new Frame ("MORE OPTIONS FOR AUCTION");
opt.setLayout (new FlowLayout());
opt.setSize (600, 360);
opt.setBackground (new Color (255, 248, 248));
opt.add (new Label ("Enter a game ID number or initial cash"));
TextField field = new TextField (10);
field.addActionListener (new SetStatusAL());
opt.add (field);
opt.add (newButton ("vs person ", new SwitchOpponentAL()));
opt.add (newButton ("gotcha!", new GotchaAL()));
opt.add (new Label ("loan compy interest-free?"));
opt.add (newButton ("loan $50", new MakeItHarderAL()));
opt.add (newButton ("use the crutch", new DisplayChoiceTreeAL()));
opt.add (area);
opt.setVisible (true);
field.requestFocus();
opt.addWindowListener (new java.awt.event.WindowAdapter()
{ public void windowClosing(java.awt.event.WindowEvent ev)
{ opt.setVisible (false);
}
});
}
}
private class MakeItHarderAL implements ActionListener // click "loan 50"
{ public void actionPerformed (ActionEvent ev)
{ status.increaseLoan (50);
9. area.append ("Compy has an advantage of " + status.getLoan() +" ");
}
}
private class DisplayChoiceTreeAL implements ActionListener // click "crutch"
{ public void actionPerformed (ActionEvent ev)
{ crutch = area;
area.append ("For each group of 3 properties between RENTs, you "
+ "have up to 8 different sequences of 3 choices. We list "
+ "here all of your choices and their consequences. "
+ "The listing is 4 columns; an entry such as 200C80 in "
+ "the first 3 columns means that on a $200 property Compy "
+ "buys it for $80. The fourth column tells how much "
+ "cash the two players (H and C) are left with after that "
+ " sequence of choices. It also tells the net change in "
+ "your cash and property holdings. ");
}
}
private class SwitchOpponentAL implements ActionListener // click "vs..."
{ public void actionPerformed (ActionEvent ev)
{ ((Button) ev.getSource()).setLabel ("vs " + twoGuys.opponent());
twoGuys.toggleOpponent();
area.append ("You are now playing against a " + twoGuys.opponent()
+ ". ");
}
}
private class SetStatusAL implements ActionListener // for options TextField
{ public void actionPerformed (ActionEvent ev)
{ TextField input = (TextField) ev.getSource();
try
{ int num = Integer.parseInt (input.getText());
if (num < 100)
area.append ("INVALID: " + num + " ");
else if (num < 1000) // 3 digits
{ status.setInitialCash (num);
area.append ("START = $" + num + " ");
}
10. else // 4 or more digits
{ status.setGameID (num);
area.append ("NEW GAME ID = " + num + " ");
}
}
catch (RuntimeException e)
{ int num = Math.abs (input.getText().hashCode());
status.setGameID (num);
area.append ("numerically, NEW GAME ID = " + num + " ");
}
input.setText ("");
input.requestFocus();
}
}
private class GotchaAL implements ActionListener // click "gotcha"
{ public void actionPerformed (ActionEvent ev)
{ Player seller = twoGuys.getFirst(); // because he lost the bid
Player buyer = twoGuys.getSecond();
int price = buyer.getPriceOfLastBuy();
if (! twoGuys.bothAreReal() || buyer.cash() < price)
return;
Label matching = seller.getMatchFor (buyer.lastPurchaseInitial());
if (matching != null)
{ area.append ("Distress sale of " + matching.getText()
+ " for a price of " + price + ". ");
buyer.makeSale (matching, seller, price);
seller.updateForIncomeReceived (price);
seller.validate();
}
}
}
} // END OF Auction CLASS
/** Called once at the beginning of each game. */
public void addHoldingsToPanel (int initialCash, int loan)
{ propAmt = 0;
cashAmt = initialCash + loan;
11. loanAmt = loan;
priceOfLastBuy = 100000;
propLabel.setText (propTag + propAmt);
cashLabel.setText (cashTag + cashAmt);
this.add (propLabel);
this.add (cashLabel);
size = NUM_BLANKS;
for (int k = NUM_BLANKS - 1; k >= 0; k--)
this.add (blanks[k]);
validate(); // re-layout components
}
public int cash()
{ return cashAmt;
}
public int prop()
{ return propAmt;
}
public int assets()
{ return cashAmt + propAmt - loanAmt;
}
public int getPriceOfLastBuy()
{ return priceOfLastBuy;
}
public void makeSale (Label prop, Panel boardPanel, int priceOfProp)
{ cashAmt -= priceOfProp;
propAmt += ((Property) prop).getCost();
priceOfLastBuy = priceOfProp;
if (size == 0)
this.add (prop);
else
{ this.add (prop, 2 + NUM_BLANKS - size); // 2,3,...
boardPanel.add (blanks[--size]); // also removes from own
}
cashLabel.setText (cashTag + cashAmt);
propLabel.setText (propTag + propAmt);
this.validate(); // re-layout components
12. }
public void updateForIncomeReceived (int increase)
{ cashAmt += (increase >= 0) ? increase : propAmt / 10;
cashLabel.setText (cashTag + cashAmt);
}
public char lastPurchaseInitial() // only called by GotchaAL
{ Component[] data = this.getComponents();
int pos = data.length - 1;
while (! (data[pos] instanceof Property))//skip blank labels
pos--;
return ((Property) data[pos]).getText().charAt (4);
}
public Label getMatchFor (char chr) // only called by GotchaAL
{ Component[] data = this.getComponents();
for (int pos = data.length - 1; pos >= 0; pos--)
{ if (data[pos] instanceof Property
&& ((Property) data[pos]).getText().charAt (4) == chr)
return (Label) data[pos];
}
return null;
}
}
class BidPrompter extends Panel
{
public static final String HUM_DOWN = " You first; bid this?";
public static final String HUM_UP = "You first; this or more?";
private Label hintLabel = new Label ("hint=000");
private Label promptForBid; // tells human what the bid choices are
private Label currentBid = new Label ("000"); // current or suggested bid
private int displayedBid = 0; // the bid showing in the currentBid label
private int bestBid = 0; // best estimate of amount to bid
private boolean bidHasBeenRaised = false;
public BidPrompter()
{ super();
promptForBid = new Label (HUM_UP, Label.RIGHT);
add (hintLabel); // using FlowLayout
14. class RentLabel extends Label
{
public RentLabel (String name)
{ super (name, Label.CENTER);
setBackground (Color.magenta);
}
public void paint (Graphics page)
{ page.setColor (Color.blue);
Dimension dim = this.getSize(); // required in Java 1.1, not getHeight()
int bottom = dim.height;
int reps = (dim.width - 2) / 8;
int x = (dim.width - 8 * reps) / 2;
page.drawLine (x, 1, x, bottom - 1);
for (; x < 8 * reps; x += 8)
{ page.drawLine (x, 1, x + 4, 5);
page.drawLine (x + 4, 5, x + 8, 1);
page.drawLine (x, bottom - 1, x + 4, bottom - 5);
page.drawLine (x + 4, bottom - 5, x + 8, bottom - 1);
}
page.drawLine (x, 1, x, bottom - 1);
}
public void flashIntermittently() // only called from prepareForNextTurn
{ long later = System.currentTimeMillis() + 1000; // 1 second
while (later > System.currentTimeMillis())
{ this.setBackground (this.getBackground() == Color.white
? Color.blue : Color.white);
for (int k = 0; k < 6000000; k++)
{ }
}
this.setBackground (Color.magenta);
}
}
class Property extends Label
{
private int itsCost;
15. public Property (int givenCost, String givenName)
{ super (givenCost + " " + givenName);
itsCost = givenCost;
}
public void paint (Graphics page)
{ page.setColor (Color.black);
Dimension dim = this.getSize(); // required in Java 1.1, not getHeight()
page.drawRect (1, 1, dim.width - 2, dim.height - 2);
}
public int getCost()
{ return itsCost;
}
}
class GameStatus extends Object // tracks status variables set once each game
{
private int initialCash = 600 + new java.util.Random().nextInt() % 3 * 50;
// nextInt()%3 is -2 to 2, so the result is 500/550/600/650/700
private int compyLoan = 0;
private int gameID = 0;
private boolean haveUsedGameID = true;
public void increaseLoan (int num) // only called by MakeItHarderAL
{ compyLoan += num;
}
public int getLoan()
{ return compyLoan;
}
public String showLoan()
{ return (compyLoan == 0) ? "" : ", loan= " + (-compyLoan);
}
public void setGameID (int num) // only called by SetStatusAL
{ gameID = num;
haveUsedGameID = false;
}
public int nextGameID()
{ if (haveUsedGameID)
gameID = 55000 + new java.util.Random().nextInt() % 45000;
16. // so the result is 10001 through 99999
haveUsedGameID = true;
return gameID;
}
public void setInitialCash (int num) // only called by SetStatusAL
{ initialCash = num;
}
public int getInitialCash()
{ return initialCash;
}
} // END OF GameStatus CLASS
class TotalGames // tracks multiple games and totals
{
private int itsNumGames = 0;
private int itsTotalScore = 0;
private int itsNumWon = 0;
public String updateTotals (int score)
{ itsTotalScore += score;
itsNumGames++;
if (score > 0)
itsNumWon++;
return " ==> GAME OVER: Your score = " + score
+ (itsNumGames == 1 ? ". "
: ". You won " + itsNumWon + " out of " + itsNumGames
+ "; your average is "
+ (itsTotalScore / itsNumGames) + ". ");
}
} // END OF TotalGames CLASS
class PropList
{
public static final int MAX = 20; // number of properties
public static final int TOTAL = MAX + 5; // allow for 4 rents + 1 cash-in
public static final int FIRST_GROUP = 9;
public static final int UNIT = Auction.UNIT;
private Label[] allData = new Label [TOTAL];
private Property[] itsProperty;
17. private Label[] fixed = {new RentLabel ("COLLECT RENT"),
new RentLabel ("COLLECT RENT"), new RentLabel ("COLLECT RENT"),
new RentLabel ("COLLECT RENT"), new RentLabel ("CASH IN")};
private int nextAvailable = 0;
private int totalOfFirstGroup;
private int valueOfFirstGroup;
public PropList()
{ itsProperty = new Property[MAX];
String[] name = {"St.Louis RR", "SantaFe RR", "B&O RR", "Boston RR",
"Arizona", "Alabama", "Connecticut", "California",
"Illinois", "Indiana", "Maryland", "Mass.",
"New York", "New Jersey", "Oregon", "Oklahoma",
"Tennessee", "Texas", "Virginia", "Vermont"};
int[] cost = {100, 100, 100, 100, 100, 100, 100, 100, 200, 200, 200, 200,
200, 200, 200, 200, 300, 300, 300, 300};
final Color RED = new Color (255, 96, 96);
final Color GRAY = new Color (216, 216, 216);
for (int k = 0; k < MAX; k++) // inefficient but only done once per game
{ itsProperty[k] = new Property (cost[k], name[k]);
itsProperty[k].setBackground (k < 4 ? GRAY : k < 8 ? Color.cyan
: k < 12 ? Color.orange : k < 16 ? RED : Color.green);
}
}
public void resetIterator (int initial)
{ nextAvailable = 0;
valueOfFirstGroup = Math.min (64 + Math.max (0, (initial - 650) / 18),
initial * 200 / (totalOfFirstGroup + 505 +
(1500-totalOfFirstGroup) / 100 * (1000-initial) / 20));
}
public Label next()
{ return allData[nextAvailable++];
}
public Label getNext()
{ return allData[nextAvailable];
}
18. public int numSold() // returns 9, 12, 15, 18 on 10, 14, 18, 22
{ return nextAvailable <= FIRST_GROUP ? nextAvailable
: (nextAvailable + 2) - (nextAvailable + 2) / 4;
}
/** Produce a random ordering of the 20 properties at the beginning of
a new game. Also calculate the total value of the first 9. */
public void shuffleToRandomize (int givenSeed)
{ java.util.Random randy = new java.util.Random (givenSeed);
Property[] copy = new Property[MAX];
System.arraycopy (itsProperty, 0, copy, 0, MAX);
for (int k = 0; k < MAX; k++)
{ int spot = k + Math.abs (randy.nextInt()) % (MAX - k);
Property temp = copy[spot];
copy[spot] = copy[k];
copy[k] = temp;
}
totalOfFirstGroup = 0;
for (int k = 0; k < FIRST_GROUP; k++)
totalOfFirstGroup += copy[k].getCost();
int pos = 0;
for (int k = 0; k < MAX; k++)
{ allData[pos++] = copy[k];
if (pos == 9 || pos == 13 || pos == 17 || pos == 21)
allData[pos++] = fixed[(pos - FIRST_GROUP) / 4];
}
allData[pos] = fixed[4];
}
public int getTotalOfFirstGroup()
{ return totalOfFirstGroup;
}
public int selectBestBid (boolean bidbyman, int initialBidder, int other,
int comPlus, TextArea options)
{ int cost = ((Property) allData[nextAvailable]).getCost();
if (nextAvailable < FIRST_GROUP) // so in the first group of 9
{ if (nextAvailable == 5 && Math.abs (comPlus) >= 200)
19. valueOfFirstGroup -= UNIT * comPlus / Math.abs (comPlus);
return Math.min (valueOfFirstGroup * cost / 100,
Math.min (initialBidder, other) + UNIT - 1);
}
if (nextAvailable < 22) // reduce to $75 per 100 except last group
cost = cost * 3 / 4;
if ( ! (allData[nextAvailable + 1] instanceof Property)) // one left
return Bid.bestBid (initialBidder, other, cost).itsBid;
int b = ((Property) allData[nextAvailable + 1]).getCost() * 3
/ (nextAvailable < 22 ? 4 : 3);
if ( ! (allData[nextAvailable + 2] instanceof Property)) // two left
return Bid.bestBid (initialBidder, other, cost, b).itsBid;
int c = ((Property) allData[nextAvailable + 2]).getCost();
Bid firstOf3 = Bid.bestBid (initialBidder, other, cost, b, c * 3 / 4);
if (options != null && bidbyman)
options.append (firstOf3.toString (bidbyman, initialBidder, other));
else if (options != null)
options.append (firstOf3.toString (bidbyman, other, initialBidder));
return firstOf3.itsBid;
}
}// END OF PropList CLASS
class Bid // only used by selectBestBid() in PropList
{
/** For "me" vs "him": "me" denotes the one who has first bid. */
public static final int UNIT = Auction.UNIT; // for convenience
private static final Bid EMPTY_BID = new Bid (-101, 10000, 100);
public final int itsBid; // always non-negative
private Bid bestBidIfKept; // not used by bestBid()
private Bid bestBidIfLost; // not used by bestBid()
private int itsGain; // gain for whoever is first; thus it may be negative
private int itsProp; // always 100 or 200 or 300
/** A bid on the last property. Precondition: itsBid % 5 is 3 or 4 */
public Bid (int bid, int gain, int prop) // only called by 3-param bestBid()
{ itsBid = bid;
itsProp = prop;
20. bestBidIfKept = EMPTY_BID;
bestBidIfLost = EMPTY_BID;
itsGain = gain;
}
/** ONE property left. THREE-parameter bestBid calls THREE-parameter Bid
constructor. It is me's bid first. All parameters are non-negative. */
public static Bid bestBid (int me, int him, int current)
{ if (me >= current && him >= current)
return new Bid (current - 1, 0, current);
else if (him > me) // so me < current
return new Bid (me + UNIT - 1, me + UNIT - current, current);
else // so him <= me && him < current
return new Bid (him + UNIT - 1, current - him, current);
}
/** A bid on the next-to-last of two properties before a RENT.
Precondition: -5 <= estimate <= minimum of other 3 parameters. */
public Bid (int estimate, int me, int him, int one, int two)
{ itsBid = estimate; // always a multiple of 5
itsProp = one;
bestBidIfKept = bestBid (him, me - estimate, two);
bestBidIfLost = (him <= estimate) ? EMPTY_BID // gain of infinity
: bestBid (me, him - estimate - UNIT, two);
itsGain = Math.min (itsProp - itsBid - bestBidIfKept.itsGain,
UNIT + itsBid - itsProp + bestBidIfLost.itsGain);
}
/** The best bid revised for an estimate 4 higher (to be overbid). */
public Bid (Bid basis)
{ this.itsBid = basis.itsBid + 4;
this.itsProp = basis.itsProp;
this.bestBidIfKept = basis.bestBidIfKept;
this.bestBidIfLost = basis.bestBidIfLost;
this.itsGain = basis.itsGain;
}
private int gainIfKept()
{ return itsProp - itsBid - bestBidIfKept.itsGain;
}
21. private int gainIfLost() // infinity if opponent cannot overbid
{ return itsBid + UNIT - itsProp + bestBidIfLost.itsGain;
}
public static Bid bestBid (int me, int him, int one, int two)
{ int estimate = Math.min (him, Math.min (me, one));
Bid high = new Bid (estimate, me, him, one, two);
if (estimate < one && high.gainIfLost() < high.gainIfKept())
return new Bid (high);
estimate -= UNIT;
Bid lower = new Bid (estimate, me, him, one, two);
while (lower.gainIfLost() > lower.gainIfKept() && estimate >= 0)
{ high = lower;
estimate -= UNIT;
lower = new Bid (estimate, me, him, one, two);
}
return (estimate < 0 || high.gainIfKept() >= lower.gainIfLost())
? high : new Bid (lower);
}
/** A bid on the third-to-last of three before a RENT. */
public Bid (int estimate, int me, int him, int one, int two, int three)
{ itsBid = estimate;
itsProp = one;
bestBidIfKept = bestBid (him, me - estimate, two, three);
bestBidIfLost = (him <= estimate) ? EMPTY_BID // gain of infinity
: bestBid (me, him - estimate - UNIT, two, three);
itsGain = Math.min (itsProp - itsBid - bestBidIfKept.itsGain,
UNIT + itsBid - itsProp + bestBidIfLost.itsGain);
}
/** THREE properties left. FIVE-parameter bestBid calls SIX-parameter Bid
constructor, which in turn calls FOUR-parameter bestBid. */
public static Bid bestBid (int me, int him, int one, int two,
int three)
{ int estimate = Math.min (him, Math.min (me, one));
Bid high = new Bid (estimate, me, him, one, two, three);
if (estimate < one && high.gainIfLost() < high.gainIfKept())
22. return new Bid (high);
estimate -= UNIT;
Bid lower = new Bid (estimate, me, him, one, two, three);
while (lower.gainIfLost() > lower.gainIfKept() && estimate >= 0)
{ high = lower;
estimate -= UNIT;
lower = new Bid (estimate, me, him, one, two, three);
}
return (estimate < 0 || high.gainIfKept() >= lower.gainIfLost())
? high : new Bid (lower);
}
private static final String BLANKS = " ";
public String toString (boolean bidbyman, int humCash, int comCash)
{ return "human has $" + humCash + "; compy has $" + comCash
+ (bidbyman ? "; human" : "; compy") + "'s bid first. "
+ "Your choices are... "
+ toString (bidbyman, "", humCash, comCash, 0, 0, 3) + " ";
}
public String toString (boolean bidbyman, String prefix, int humCash,
int comCash, int cahead, int pahead, int level)
{ if (humCash < 0 || comCash < 0)
return ""; // skip this line, since it is impossible by the rules
int padding = Math.max (0, 30 - prefix.length());
if (this == EMPTY_BID) // only after 3 bids
return prefix + BLANKS.substring (0, padding)
+ " H$" + humCash + ": C$" + comCash + " so cash: "
+ cahead + ", prop: " + (pahead * 4 / 3)
+ ", net= " + (cahead + pahead * 4 / 3) + " ";
int loBid = itsBid - itsBid % UNIT;
boolean goUp = itsBid % UNIT > UNIT / 2;
int comPaid = bidbyman ? loBid + UNIT : loBid;
Bid comBid = bidbyman ? bestBidIfLost : bestBidIfKept;
int humPaid = bidbyman ? loBid : loBid + UNIT;
Bid humBid = bidbyman ? bestBidIfKept : bestBidIfLost;
if (bidbyman && goUp && comCash > itsBid) // can bid more to get it
{ humPaid = loBid + UNIT;