MaryEllen Volb

Ranch Hand
+ Follow
since Jan 31, 2001
Cows and Likes
Cows
Total received
0
In last 30 days
0
Total given
0
Likes
Total received
0
Received in last 30 days
0
Total given
0
Given in last 30 days
0
Forums and Threads
Scavenger Hunt
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt

Recent posts by MaryEllen Volb

HI,
the compiler error I got was "method does not return a value;return type required" where the threads start in the program. If you can help at all, I'd appreciate it!!!
Thanks, Mary Ellen
Hello
I have to modify this program in two ways, and I am a REAL newbie.......PLEASE HELP.
1) Rewrite the program using fileReader and FileWriter streams
2) Write another program with buffered streams to boost performance.

import java.io.*;
public class CopyFileUsingByteStream
{
// Main method: args[0] for sourcefile and args[1] for target file
public static void main(String[] args)
{
// Declare input and output file streams
FileInputStream fis = null;
FileOutputStream fos = null;
// Check usage
if (args.length !=2)
{
System.out.println(
"Usage: java CopyFileUsingByteStream fromfile tofile");
System.exit(0);
}
try
{
// Create file input stream
fis = new FileInputStream(new File(args[0]));
// Create file output stream if the file does not exist
File outFile = new File(args[1]);
if (outFile.exists())
{
System.out.println("file " + args[1] + " already exists");
return;
}
else
fos = new FileOutputStream(args[1]);
// Display the file size
System.out.println("The file " + args[0] + " has "+
fis.available() + " bytes");
// Continuously read a byte from fis and write it to fos
int r;
while ((r = fis.read()) != -1)
fos.write((byte)r);
}
catch (FileNotFoundException ex)
{
System.out.println("File not found: " + args[0]);
}
catch (IOException ex)
{
System.out.println(ex.getMessage());
}
finally
{
try
{
// Close files
if (fis != null) fis.close();
if (fos != null) fos.close();
}
catch (IOException ex)
{
System.out.println(ex);
}
}
}
}
THANKS !!! Mary Ellen
19 years ago
Hello,
I have to print three threads simultaneously to a text area. I think I have what I need in this program, but I am still getting compiler errors. Any suggestions?
Thanks, Mary Ellen
package Chapter13;
import Chapter8.MyFrameWithExitHandling;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PrintThreadsToTextArea extends MyFrameWithExitHandling
implements ActionListener
{
private JTextArea jta;
//public StringBuffer buf = new StringBuffer();
public JButton jbt;

// Main method
public static void main(String[] args)
{
PrintThreadsToTextArea frame = new PrintThreadsToTextArea();
frame.pack();
frame.center();
frame.setSize(400,300);
frame.setVisible(true);
}

//Constructor
public PrintThreadsToTextArea()
{
setTitle("Print Threads to Text Area");
//Create panel p to hold the tesxt field
JPanel p = new JPanel();
p.setLayout(new FlowLayout());
p.add(jta = new JTextArea());
//Create scroll pane to hold text area
JScrollPane scrollPane = new JScrollPane(jta = new JTextArea());
//set line wrap
jta.setLineWrap(true);
//set FlowLayout for the frame and add components to it
getContentPane().setLayout(new BorderLayout());
getContentPane().add(scrollPane, BorderLayout.CENTER);
getContentPane().add(p, BorderLayout.SOUTH);
//register listeners
jta.addActionListener(this);
jbt.addActionListener(this);
}
//Action event handler
// Create threads
PrintChar printA = new PrintChar('a', 100);
PrintChar printB = new PrintChar('b', 100);
PrintNum print100 = new PrintNum(100);
// Start threads
print100.start();
printA.start();
printB.start();
public void actionPerformed(ActionEvent e)
{
jta.append(jta.getText().trim());
}
// The thread class for printing a specified character
// in specified times
class PrintChar extends Thread
{
private char charToPrint;
private int times;
public PrintChar(char c, int t)
{
charToPrint = c;
times = t;
}
// Override the run() method to tell the system
// what the thread will do
public void run()
{
for (int i=1; i < times; i++)
System.out.print(charToPrint);
}
}
class PrintNum extends Thread
{
private int lastNum;

public PrintNum(int n)
{
lastNum = n;
}
public void run()
{
for (int i=1; i <= lastNum; i++)
System.out.print(" " + i);
}
}
}
THANK YOU THANK YOU THANK YOU!!!
19 years ago
Hi,
This program was modified not to draw a rectangle when the mouse was pressed, but to show the pixel location instead. The program compiles, runs, but doesn't show the pixel location when mouse is clicked. If someone can find my error, I'd be VERY grateful!!!

THANKS!!! Mary Ellen

MousePositionInPixels.java--This program modifies the Chapter 8 program
TestMouseEvent.java. Instead of filling a square when a mouse click is
detected, the location of the mouse click in pixels will appear on the
screen.*/
package Chapter8;
import java.awt.event.*;
import javax.swing.*;
import java.awt.Graphics;
import java.awt.*;
public class MousePositionInPixels extends MyFrameWithExitHandling
implements MouseListener
{
private int x, y = 0; // x, y coordinates
// Default constructor
public MousePositionInPixels()
{
setTitle("MousePositionInPixels");
addMouseListener(this); // Register listener
}
// Main method
public static void main(String[] args)
{
MousePositionInPixels frame = new MousePositionInPixels();
frame.setSize(200, 200);
frame.setVisible(true);
}
// When the mouse is pressed, the mouse pointer location
// will be stored in (x, y)
public void mousePressed(MouseEvent e)
{
// Get (x, y) coordinates using getX() and getY() methods
x = e.getX();
y = e.getY();
repaint();
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
public void drawString(Graphics g)
{
String s ="The mouse is at x=" + x + " and y=" + y;
g.drawString(s, x, y );
}
}
19 years ago
HI,
This is a program that compiles but doesn't run. I get the error that the constructor rectangle[i]= new CompareRectangle is a malformed expression. Could someone help with this?
THANKS!!! Mary Ellen
CompareRectangle.java--This program will create a class named CompareRectangle
that will extend Rectangle and implement CompareObject. Implementation of the compareTo() method that will compare the rectangles on their areas will occur. A test class will be written to sort a list of CompareRectangle objects.*/
package Chapter7;
public class CompareRectangle extends Rectangle implements CompareObject
{
public static void main(String[] args)
{
//Create rectangles
CompareRectangle[] rectangle = new CompareRectangle[10];
for (int i = 0; i<rectangle.length; i++);>
rectangle[i] = new CompareRectangle(100*Math.random(),5.0, 8.0, "white");

//Construct a CompareRectangle with specified area and color
public CompareRectangle(double width, double height, double w, String c)
{
super(w, c);
}

//Implement compare method defined in CompareObject
public int compareTo(CompareObject otherObject)
{
Rectangle rectangle = (Rectangle)otherObject;
if(findArea() < rectangle.findArea())
return LESS;
else if (findArea() == rectangle.findArea())
return EQUAL;
else return GREATER;
}
public String toString()
{
return "The rectangle area is: " + findArea();
}
}
}
19 years ago
Gareth,
You rule!!! I mean....thanks
Mary Ellen
19 years ago
HI!
Could somebody try to compile this code and maybe tell me what is wrong? It compiles and runs, but the future value calculation comes out wrong. Any help is appreciated!!!
Mary Ellen

FutureValue.java--This program will calculate the future value of an investment
at a given interest rate for a specified number of years. The program will
enable the user to enter the interest reat, investment amount, and years to
predefined text fields set by the programmer. The future value will be
displayed when the user clicks on the "calculate" button.
*/

(edited by Cindy to format code)
[This message has been edited by Cindy Glass (edited April 13, 2001).]
19 years ago
HI!
Could somebody try to compile this code and maybe tell me what is wrong? It compiles and runs, but the future calue calculation comes out wrong. Any help is appreciated!!!
Mary Ellen

FutureValue.java--This program will calculate the future value of an investment
at a given interest rate for a specified number of years. The program will
enable the user to enter the interest reat, investment amount, and years to
predefined text fields set by the programmer. The future value will be
displayed when the user clicks on the "calculate" button.
*/
package Chapter9;
import Chapter8.MyFrameWithExitHandling;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.Math;
import java.util.*;
import java.text.*;
public class FutureValue extends MyFrameWithExitHandling
implements ActionListener
{
// Declare three text fields
private JTextField jtfld1, jtfld2, jtfld3, jtfldResult;
// Declare "Calculate" Button
private JButton jbtCalculate;
// Declare two menu options
private JMenuItem jmiCalculate, jmiAbout;
Locale locale = Locale.ENGLISH;
// Main method
public static void main(String[] args)
{
FutureValue frame = new FutureValue();
//frame.pack();
frame.setSize(225, 210);
frame.center();
frame.setVisible(true);
}
// Constructor
public FutureValue()
{
setTitle("Future Value");
setBackground(Color.yellow);
setForeground(Color.black);
JMenuBar jmb = new JMenuBar();
setJMenuBar(jmb);
// set operation menu
JMenu operationMenu = new JMenu("Operation");
operationMenu.setMnemonic('O');
jmb.add(operationMenu);
// set help menu
JMenu helpMenu = new JMenu("Help");
operationMenu.setMnemonic('H');
jmb.add(helpMenu);
// add menu items with pneumonics
operationMenu.add(jmiCalculate= new JMenuItem("Calculate", 'C'));
helpMenu.add(jmiAbout = new JMenuItem("About", 'A'));
// Use panel p1 to group label fields
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(4,1));
p1.add(new Label("Investment"));
p1.add(new Label("Years"));
p1.add(new Label("Interest Rate"));
p1.add(new Label("Future Value"));
// Use Panel p2 to group text fields
JPanel p2 = new JPanel();
p2.setLayout(new GridLayout(4,1));
p2.add(jtfld1 = new JTextField(10));
p2.add(jtfld2 = new JTextField(10));
p2.add(jtfld3 = new JTextField(10));
p2.add(jtfldResult = new JTextField(10));
jtfldResult.setEditable(false); // Set jtfResult noneditable
// Use panel p2 for the button
JPanel p3 = new JPanel();
p3.setLayout(new FlowLayout());
p3.add(jbtCalculate = new JButton("Calculate"));
// Set FlowLayout for the frame and add panels to the frame
getContentPane().setLayout(new BorderLayout());
getContentPane().add(p1, BorderLayout.WEST);
getContentPane().add(p2, BorderLayout.CENTER);
getContentPane().add(p3, BorderLayout.SOUTH);
// Register listener
jbtCalculate.addActionListener(this);
jmiCalculate.addActionListener(this);
jmiAbout.addActionListener(this);
}
// Handle the add operation
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
// Handle button events
if (e.getSource() instanceof JButton)
{
calculate('n');
}
// Handle Menuitem events
else if (e.getSource() instanceof JMenuItem)
{
if ("Calculate".equals(actionCommand))
calculate('n');
else if ("About".equals(actionCommand))
JOptionPane.showMessageDialog(this, "Adapted with help",
"For Your Information", JOptionPane.INFORMATION_MESSAGE);
}
}
private void calculate(char operator)
{
float investmentAmount = (Float.parseFloat(jtfld1.getText().trim()));
float yrs = (Float.parseFloat(jtfld2.getText().trim()));
float interestRate = (Float.parseFloat(jtfld3.getText().trim()));
float firstPart = investmentAmount * (1 + interestRate);
double futureValue = Math.pow(firstPart,yrs);
// Set result in TextField jtfResult
jtfldResult.setText(String.valueOf(futureValue));
}
}
19 years ago
Hello!
As a class assignment, I have to modify the following code to display the output to a text area(instead of just to the DOS window). Any hints as to how I should attempt this? THANKS!!!
This program creates and runs three threads.
first prints letter 'a' 100 times.
second prints letter 'b' 100 times.
third prints integers 1 through 100.
NOW: I NEED IT TO PRINT TO A TEXT AREA, NOT TO THE DOS WINDOW!

Thanks again, MARY ELLEN!
// TestThreads.java: Define threads using the Thread class
package Chapter13;
public class TestThreads
{
// Main method
public static void main(String[] args)
{
// Create threads
PrintChar printA = new PrintChar('a', 100);
PrintChar printB = new PrintChar('b', 100);
PrintNum print100 = new PrintNum(100);
// Start threads
print100.start();
printA.start();
printB.start();
}
}
// The thread class for printing a specified character
// in specified times
class PrintChar extends Thread
{
private char charToPrint; // The character to print
private int times; // The times to repeat
// Construct a thread with specified character and number of
// times to print the character
public PrintChar(char c, int t)
{
charToPrint = c;
times = t;
}
// Override the run() method to tell the system
// what the thread will do
public void run()
{
for (int i=1; i < times; i++)
System.out.print(charToPrint);
}
}
// The thread class for printing number from 1 to n for a given n
class PrintNum extends Thread
{
private int lastNum;
// Construct a thread for print 1, 2, ... i
public PrintNum(int n)
{
lastNum = n;
}
public void run()
{
for (int i=1; i <= lastNum; i++)
System.out.print(" " + i);
}
}
19 years ago
Hi,
Our instructor showed us a way to use swingall.jar to view applets in a browser, but I can't get it to work. I use JBuilder, and I know there is a way to use applet viewer, but I don't know how. Can anyone help???
Thanks, Mary Ellen
19 years ago
Sorry!!!
I know it's alot of code, but I was just wondering if there is some way to insert some code that will stop the player from being able to continue to click on cells after the game has been won. I think that is really all this program requires.
thanks, Mary Ellen
19 years ago
Hi,
i have to modify this code to declare Cell as a standalone class instead of an inner class, and, when the game is over, the user should not be able to click the empty cells to mark them. Can you give me a clue? Yes this is a class assignment!

// TicTacToe.java: Play the TicTacToe game
package Chapter10;
import java.awt.*;
import Chapter8.MyFrameWithExitHandling;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
public class TicTacToe extends JApplet
{
// Indicate which player has a turn, initially it is the X player
private char whoseTurn = 'X';
// Create and initialize cells
private Cell[][] cell = new Cell[3][3];
// Create and initialized a status label
private JLabel jlblStatus = new JLabel("X's turn playing");
// Initialize UI
public void init()
{
// Panel p to hold cells
JPanel p = new JPanel();
p.setLayout(new GridLayout(3, 3, 0, 0));
for (int i=0; i<3; i++)
for (int j=0; j<3; j++)
p.add(cell[i][j] = new Cell());
// Set line borders on the cells panel and the status label
p.setBorder(new LineBorder(Color.red, 1));
jlblStatus.setBorder(new LineBorder(Color.yellow, 1));
// Place the panel and the label to the applet
this.getContentPane().add(p, BorderLayout.CENTER);
this.getContentPane().add(jlblStatus, BorderLayout.SOUTH);
}
// This main method enables the applet to run as an application
public static void main(String[] args)
{
// Create a frame
MyFrameWithExitHandling frame = new MyFrameWithExitHandling(
"Mouse Drawing Demo");
// Create an instance of the applet
TicTacToe applet = new TicTacToe();
// Add the applet instance to the frame
frame.getContentPane().add(applet, BorderLayout.CENTER);
// Invoke init() and start()
applet.init();
applet.start();
// Display the frame
frame.setSize(300, 300);
frame.setVisible(true);
}
// Determine if the cells are all occupied
public boolean isFull()
{
for (int i=0; i<3; i++)
for (int j=0; j<3; j++)
if (cell[i][j].getToken() == ' ')
return false;
return true;
}
// Determine if the player with the specified toekn wins
public boolean won(char token)
{
for (int i=0; i<3; i++)
if ((cell[i][0].getToken()==token)
&& (cell[i][1].getToken()==token)
&& (cell[i][2].getToken()==token))
{
return true;
}
for (int j=0; j<3; j++)
if ((cell[0][j].getToken()==token)
&& (cell[1][j].getToken()==token)
&& (cell[2][j].getToken()==token))
{
return true;
}
if ((cell[0][0].getToken()==token)
&& (cell[1][1].getToken()==token)
&& (cell[2][2].getToken()==token))
{
return true;
}
if ((cell[0][2].getToken()==token)
&& (cell[1][1].getToken()==token)
&& (cell[2][0].getToken()==token))
{
return true;
}
return false;
}
// An inner class for a cell
public class Cell extends JPanel implements MouseListener
{
// Token used for this cell
private char token = ' ';
public Cell()
{
setBorder(new LineBorder(Color.black, 1)); // Set cell's border
addMouseListener(this); // Register listener
}
// The getter method for token
public char getToken()
{
return token;
}
// The setter method for token
public void setToken(char c)
{
token = c;
repaint();
}
// Paint the cell
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if (token == 'X')
{
g.drawLine(10, 10, getSize().width-10, getSize().height-10);
g.drawLine(getSize().width-10, 10, 10, getSize().height-10);
}
else if (token == 'O')
{
g.drawOval(10, 10, getSize().width-20, getSize().height-20);
}
}
// Handle mouse click on a cell
public void mouseClicked(MouseEvent e)
{
if (token == ' ') // If cell is not occupied
{
if (whoseTurn == 'X') // If it is the X player's turn
{
setToken('X'); // Set token in the cell
whoseTurn = 'O'; // Change the turn
jlblStatus.setText("O's turn"); // Display status
if (won('X'))
jlblStatus.setText("X won! The game is over");
else if (isFull())
jlblStatus.setText("Draw! The game is over");
}
else if (whoseTurn == 'O') // If it is the O player's turn
{
setToken('O'); // Set token in the cell
whoseTurn = 'X'; // Change the turn
jlblStatus.setText("X's turn"); // Display status
if (won('O'))
jlblStatus.setText("O won! The game is over");
else if (isFull())
jlblStatus.setText("Draw! The game is over");
}
}
}
public void mousePressed(MouseEvent e)
{
//TODO: implement this java.awt.event.MouseListener method;
}
public void mouseReleased(MouseEvent e)
{
//TODO: implement this java.awt.event.MouseListener method;
}
public void mouseEntered(MouseEvent e)
{
//TODO: implement this java.awt.event.MouseListener method;
}
public void mouseExited(MouseEvent e)
{
//TODO: implement this java.awt.event.MouseListener method;
}
}
}
19 years ago
AS always, THANKS FOR YOUR HELP!!!
19 years ago
Hi,
Yes another dreaded assignment......I have to, instead of drawing a filled box, give the user the position of the mouse click in pixels when the mouse is clicked on the screen. Any cluse as to how I could modify this program to do that?
Thanks, Mary Ellen

(edited by Cindy to add formatting)

[This message has been edited by Cindy Glass (edited March 31, 2001).]
19 years ago