| | |
Help With an error
Please support our Java advertiser: Programming Forums - DaniWeb Sister Site
![]() |
•
•
Join Date: Mar 2005
Posts: 91
Reputation:
Solved Threads: 1
i am some what new to java so i am not really familiar with all the errors and such but i am getting one that says this:
what does that mean?
the program is suppose to be able to save and open a file of employees
Java Syntax (Toggle Plain Text)
Exception in thread "main" java.lang.ClassCastException: lab8ab.EmployeeAryApplicEx cannot be cast to lab8ab.EmployeeMultiTypeSeqFileExer at lab8ab.EmployeeMultiTypeOpenListener.<init>(EmployeeMultiTypeOpenListener.java:22) at lab8ab.EmployeeAryApplicEx.<init>(EmployeeAryApplicEx.java:115) at lab8ab.EmployeeAryApplicEx.main(EmployeeAryApplicEx.java:43)
what does that mean?
the program is suppose to be able to save and open a file of employees
You are trying to turn a EmployeeAryApplicEx instance into a EmployeeMultiTypeSeqFileExer, which cannot be done. I presume that you wrote something like this:
What you did is like trying to cast a String into an Integer:
Which cannot be done in both cases because the objects are not of the same type.
It would have worked if one object extended the other
Java Syntax (Toggle Plain Text)
EmployeeAryApplicEx empAryApplicEx=new EmployeeAryApplicEx(); EmployeeMultiTypeSeqFile empMultiTypeSeqFileExer=new EmployeeMultiTypeSeqFileExer(); empMultiTypeSeqFileExer = (EmployeeMultiTypeSeqFile)empAryApplicEx;
What you did is like trying to cast a String into an Integer:
Java Syntax (Toggle Plain Text)
String s="3"; Integer integ=(Integer)s;
Which cannot be done in both cases because the objects are not of the same type.
It would have worked if one object extended the other
Check out my New Bike at my Public Profile at the "About Me" tab
•
•
Join Date: Mar 2005
Posts: 91
Reputation:
Solved Threads: 1
makes sense but where the error takes you to is a part where my teacher gave us code and we had to expand on it. the code worked fine then and i made no changes to that part
My EmployeeMultiTypeOpenListener: error line in red
My EmployeeAryApplicEx: error lines in red
i did nothing to the error lines which is why im getting confused
My EmployeeMultiTypeOpenListener: error line in red
package lab8ab;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.text.*;
// Purpose: To handle an event caused by user selection of Open action from GUI
public class EmployeeMultiTypeOpenListener implements ActionListener {
private EmployeeMultiTypeSeqFileExer fr; // Hold reference to JFrame subclass instance
private DataInputStream input; // Stream for inputting data from file
private File selectedFile; // The file selected by user
private String path = "C:\\"; // Path for file selection dialog
// Constructor
public EmployeeMultiTypeOpenListener( JFrame f, String pt ) {
fr = (EmployeeMultiTypeSeqFileExer)f;
path = pt;
}
// Perform action using the file Open operation selected by user from menu
public void actionPerformed( ActionEvent e ) {
JFileChooser JFChoose = new JFileChooser(path);
int result = JFChoose.showOpenDialog( fr );
selectedFile = JFChoose.getSelectedFile();
// Respond to a user press of the Cancel button
if ( result == JFileChooser.CANCEL_OPTION )
return;
try { // try to create an object representing the user-selected file
input = new DataInputStream( new FileInputStream( selectedFile ) );
}
catch ( Exception ex ) {
System.out.println( "\nIn FileOpenHandlerM, Open try block: " + ex.toString() );
}
try { // try to read the file and create a string consisting of its contents
char ch;
fr.setEmployeeCount( 0 );
String name;
int idNumber = 0;
String empType = null;
String department = null;
double payRate = 0;
double hoursWorked;
do { // read data from the file until end of file is reached
name = "";
ch = input.readChar();
while ( ch != ';' ) {
name = name + ch;
ch = input.readChar();
}
while (ch != ';'){
idNumber = idNumber + ch;
idNumber = input.readInt();
}
while (ch != ';'){
empType = empType + ch;
ch = input.readChar();
}
while (ch != ';'){
department = department + ch;
ch = input.readChar();
}
while (ch != ';'){
payRate = payRate + ch;
payRate = input.readDouble();
}
hoursWorked = input.readDouble();
fr.addEmployeeToArray( idNumber, name, empType, department, payRate, hoursWorked );
} while ( true );
}
catch ( Exception ex ) {
System.out.println( "\nIn FileOpenHandler, Read try block: " + ex.toString() );
}
//fr.setMessageToUser( "Opened and read the file: " + selectedFile.getName() );
fr.displayEmployeeData();
try { // try to close the file
input.close();
}
catch ( Exception ex ) {
System.out.println( "\nIn FileOpenHandler, Close try block: " + ex.toString() );
}
}
}My EmployeeAryApplicEx: error lines in red
package lab8ab;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.io.*;
public class EmployeeAryApplicEx extends JFrame {
private String docPath = "C:\\Documents and Settings\\grupka\\My Documents\\";
// Prompts for user input
private JLabel label1, label2, label3, label4, label6, label7, label8, label9;
// Mechanisms for user input
private JTextField textfield1, textfield2, textfield3, textfield4, textfield5, textfield6;
private JComboBox typeJCB1,typeJCB2; // The JComboBox for type selection
private JButton openButton, // Button to initiate an open file action
saveButton, // Button to initiate a save file action
saveTextButton; // Button to initiate an action to save text version
// Mechanism for output display
private JTextArea textDisplay; // Output display area
private int textDisplayWidth = 25; // Width of the JTextArea
private int textDisplayHeight = 18; // Height of the JTextArea
private boolean cannotAddFlag = false; // Indicates whether employee can be added
private final int MAX_EMPLOYEES = 10; // The maximum number of employees allowed
private int countEmployees = 0; // The number of employees added to array
private String pRate = "";
private String hr = "";
private Employee employeeArray [] = new Employee[MAX_EMPLOYEES];
private String typeNames[] = {"Hourly","Salaried","Union"};
private String selectedType = "";
private String depName[] = {"Customer Service","Drafting","Engineering","Quality Control","Sales","Shipping"};
private String depN = "";
// The main method required for an application program
public static void main( String[] args ) {
JFrame frame = new EmployeeAryApplicEx( ); // Construct the window
frame.setSize( new Dimension( 360, 470 ) ); // Set its size
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible( true ); // Make the window visible
}
public EmployeeAryApplicEx() {
super("XYZ CORPORATION EMPLOYEES");
setLayout( new BorderLayout() );
JPanel jpan = new JPanel();
jpan.setLayout(new GridLayout(8,2));
jpan.setBorder(new EtchedBorder());
add(jpan,BorderLayout.NORTH);
// Create prompt and input mechanism to get employee number from user
label1 = new JLabel("Number of Employees:");
jpan.add( label1);
textfield1 = new JTextField( 3 );
textfield1.setEditable(false);
textfield1.setText(Integer.toString(countEmployees));
jpan.add( textfield1 ); // put input JTextField on JPanel
label2 = new JLabel("Max # of Employees:");
jpan.add( label2 );
textfield2 = new JTextField( 3);
textfield2.setText(Integer.toString(MAX_EMPLOYEES));
textfield2.setEditable(false);
jpan.add( textfield2 ); // put input JTextField on JPanel
// Create prompt and input mechanism to get employee type from user
label6 = new JLabel("Employee Type:");
jpan.add( label6 );
typeJCB1 = new JComboBox(typeNames);
typeJCB1.setMaximumRowCount(3);
jpan.add( typeJCB1 ); // put input JTextField on JPanel
label7 = new JLabel("Employee Department");
jpan.add( label7 );
typeJCB2 = new JComboBox(depName);
typeJCB2.setMaximumRowCount(6);
jpan.add( typeJCB2 );
// Create prompt and input mechanism to get employee name from user
label3 = new JLabel("Name:");
jpan.add( label3 );
textfield3 = new JTextField( 15 );
jpan.add( textfield3 ); // put input JTextField on JPanel
// Create prompt and input mechanism to get employee number from user
label4 = new JLabel("Employee ID Number:");
jpan.add( label4 );
textfield4 = new JTextField( Integer.toString(countEmployees+2), 15 );
jpan.add( textfield4 ); // put input JTextField on JPanel
label8 = new JLabel("Employee Pay Rate $");
jpan.add(label8);
textfield5 = new JTextField(9);
jpan.add (textfield5);
label9 = new JLabel("Hours Worked");
jpan.add (label9);
textfield6 = new JTextField(9);
jpan.add(textfield6);
// Create button panel for file operations
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 2));
buttonPanel.setBorder(new TitledBorder("File Operations"));
// Create button for Open File action, attach ActionListener, add to GUI
openButton = new JButton("Open File");
openButton.addActionListener(new EmployeeMultiTypeOpenListener(this, docPath));
buttonPanel.add(openButton);
// Create button for Save File action, attach ActionListener, add to GUI
saveButton = new JButton("Save File");
saveButton.addActionListener(new EmployeeMultiTypeSaveListener(this, docPath));
buttonPanel.add(saveButton);
add(buttonPanel, BorderLayout.SOUTH);
// Set up JTextArea to display information on all the employees
textDisplay = new JTextArea( getDataStringAllEmployees(),
textDisplayHeight,textDisplayWidth);
textDisplay.setLineWrap( true );
textDisplay.setWrapStyleWord( true );
textDisplay.setBorder(new TitledBorder("Employee List"));
add(textDisplay,BorderLayout.CENTER);
// Listener will respond to a user hitting Enter in any JTextField
MyActionListener myActListener = new MyActionListener();
textfield3.addActionListener( myActListener );
textfield4.addActionListener( myActListener );
textfield5.addActionListener( myActListener );
textfield6.addActionListener( myActListener );
// Listener will respond to a user selecting from JComboBox
MyItemListener myItemListener = new MyItemListener();
typeJCB1.addItemListener(myItemListener);
typeJCB2.addItemListener(myItemListener);
// Display data on all Employees in the JTextArea
displayEmployeeData();
}
private void displayEmployeeData(){
setDisplayFields();
textDisplay.setText(getDataStringAllEmployees());
}
// Create and insert the new employee into array
private void addEmployeeToArray( String id, String nam, String typ, String d, String pRate, String hr){
if ( countEmployees < MAX_EMPLOYEES ) {
Employee P = null; //new Employee(nam, Integer.parseInt(id), typ, depN);
if(typeNames[typeJCB1.getSelectedIndex()].equals(typeNames[0])){
P = new HourlyEmployee(nam, typ, d, Integer.parseInt(id), Double.parseDouble(pRate), Double.parseDouble(hr));
}else if(typeNames[typeJCB1.getSelectedIndex()].equals(typeNames[1])){
P = new SalariedEmployee(nam, typ, d, Integer.parseInt(id), Double.parseDouble(pRate), Double.parseDouble(hr));
} else {
P = new UnionEmployee(nam, typ, d, Integer.parseInt(id), Double.parseDouble(pRate), Double.parseDouble(hr));
}
employeeArray[countEmployees] = P;
countEmployees++;
}
}
// Return the employee instance (object) correponding to the pNumb parameter
private Employee getEmployeeFromArray( int pNumb ) {
Employee P = null;
if ( pNumb < countEmployees ) {
P = employeeArray[pNumb];
}
return P;
}
// Set the contents of the JTextFields
private void setDisplayFields() {
textfield1.setText( Integer.toString(countEmployees) );
textfield2.setText( Integer.toString(MAX_EMPLOYEES) );
textfield3.setText("");
textfield4.setText("");
textfield5.setText("");
textfield6.setText("");
}
// Get the string comprised of all the data on all employees
private String getDataStringAllEmployees() {
String displayStr = "";
// Add the information on all employees to the display string
//displayStr = displayStr + "\n XYZ CORPORATION EMPLOYEES:\n\n ";
for ( int i = 0; i < countEmployees; i++ ) {
displayStr += (i+1) + ". " + employeeArray[i].toString() + "\n ";
}
if ( cannotAddFlag )
displayStr += "\nCannot add employees - the array is full\n";
return displayStr;
}
class MyActionListener implements ActionListener {
// Process user's action in JTextField input
public void actionPerformed(ActionEvent e) {
if ( countEmployees < MAX_EMPLOYEES ) {
String name = textfield3.getText();
String idNumber = textfield4.getText();
pRate = textfield5.getText();
hr = textfield6.getText();
addEmployeeToArray(idNumber, name, selectedType, depN, pRate, hr);
} else {
cannotAddFlag = true;
}
displayEmployeeData();
}
}
class MyItemListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
// If one of the items in the JComboBox was selected,
// set the selectedDept variable to the user's selection
if (e.getSource() == typeJCB1) {
selectedType = typeNames[typeJCB1.getSelectedIndex()];
} else if(e.getSource() == typeJCB2) {
depN = depName[typeJCB2.getSelectedIndex()];
}
}
}
}i did nothing to the error lines which is why im getting confused
![]() |
Similar Threads
- Code 19 Registry Error (Windows NT / 2000 / XP)
- Error Loading operating System (Windows NT / 2000 / XP)
- svchost.exe error (Windows NT / 2000 / XP)
- New Hardware Causing Error (Windows NT / 2000 / XP)
- office 2000 install error (Windows NT / 2000 / XP)
- VMWare Unrecoverable Error (*nix Software)
- Error in Wrox Book (Perl)
Other Threads in the Java Forum
- Previous Thread: Need Help with Moving Cars
- Next Thread: display the System.out.print msgs
Views: 524 | Replies: 5
| Thread Tools | Search this Thread |
Tag cloud for Java
3d @param affinetransform android api apple applet application arc arguments array arrays automation binary bluetooth byte c# chat class classes click client code compare component corrupted database detection draw eclipse error event exception file fractal game givemetehcodez graphics gui guitesting helpwithhomework html ide image input integer j2me java java.xls javaprojects jmf jni jpanel julia keytool linux list loop map method methods mobile netbeans newbie number object oracle os pong print problem producer program programming project projectideas read recursion reflection replaysolutions rim scanner screen server set size sms socket sort sql string swing terminal test threads time transfer tree web windows






