Stop a known compile error (Cannot resolve symbol)
I get a known compile error is their some way to stop this.
Basically I call a reader in a method in my main class to be used in a threaded search.
I only reset the reader when I want to so I can search for further results without starting from the start of the file again.
I know that there is no way for the program to get to this point without having the filereader class loaded so I want to stop this error.
Im thinking their is probably a way of putting in an if statement around my call to the search thread to check the object is in memory.
Thanks for the help in advance.
I get a known compile error is their some way to stop this. Yes, fix the code so it's syntactically correct. That's the only way to get rid of compiler errors.
Im thinking their is probably a way of putting in an
if statement around my call to the search thread to
check the object is in memory.This isn't C/C++ with #define and #ifdef for preprocessor directives. What are you thinking?
Fix your code and the compiler errors will go away.
%
Similar Messages
-
Compiling error - cannot resolve symbol
Hi,
I am working on writing out this basic code for a project. When I compile, I get an error "Cannot resolve symbol" for the gpa variable. Please help!
My intention is to use the hours and points from the crHours and nbrPoints methods, and use them to calculate GPA in the grPtAvg method:
public class Student
public static void main(String[]args)
idNum();
crHours();
nbrpoints();
gpa = grPtAvg(hours, points);
System.out.println("Student's GPA is " + gpa);
public static void idNum()
int id = 2520;
System.out.println("Student's ID is " + id);
public static float crHours()
float hours = 5;
System.out.println("Student's credit hours are " + hours);
return hours;
public static float nbrpoints()
float points = 22;
System.out.println("Student's earned points are " + points);
return points;
public static float grPtAvg(float hours, float points)
float gpa;
gpa = points / hours;
System.out.println("Student's computed GPA is " + gpa);
return gpa;That's because you're doing the same thing (in a somewhat different way) with those.
The variables: hours and points have already been returned to main methd, right?Yes, but then the main method ignores them.
So, they should be available at this point in the code, is that right?Available in the sense that you can read them, but not in the sense that there are hours and points variables within scope in the main method.
You want to do this:
public static void main(String[] args) {
idNum();
float hours = crHours();
float points = nbrpoints();
//create a new float
float myComputetdGpa = grPtAvg(hours, points);
System.out.println("Student's GPA is " + myComputedGpa);
} -
Compiler error cannot resolve symbol
Hi people,
i'm having this compile time error that, when i create a class and calling that class in another class gives the error cannot resolve symbol classname and it also happened when i created a bean and referencing the bean class in another bean when i'm using Jsp. thanks in advance.It would be helpful if you post the exact error message. If you use a system Classpath, then it must contain the root directory for the package directory(s).
For example, if the source code for a file starts with
package my.package;
and you have a directory structure c:\myjava\classes\my\package then the Classpath must contain c:\myjava\classes. -
Javac compiler Error - cannot resolve symbol - symbol StringBuilder?
Hi ,
I am using hp - ux system with java version "1.4.2.06". when i try to compile a program called CharSequenceDemo.java which is found in the java tutorials at this link
[CharSequenceDemo.java|http://java.sun.com/docs/books/tutorial/java/IandI/examples/CharSequenceDemo.java]
i get the following error:
$/opt/java1.4/bin/javac CharSequenceDemo.java
CharSequenceDemo.java:38: cannot resolve symbol
symbol : class StringBuilder
location: class CharSequenceDemo
StringBuilder sub =
^
CharSequenceDemo.java:39: cannot resolve symbol
symbol : class StringBuilder
location: class CharSequenceDemo
new StringBuilder(s.subSequence(fromEnd(end), fromEnd(start)));
^
CharSequenceDemo.java:44: cannot resolve symbol
symbol : class StringBuilder
location: class CharSequenceDemo
StringBuilder s = new StringBuilder(this.s);
^
CharSequenceDemo.java:44: cannot resolve symbol
symbol : class StringBuilder
location: class CharSequenceDemo
StringBuilder s = new StringBuilder(this.s);
^
4 errors
Please help on how to compile this program.I've been struggling with the same issue. The difference is that my system says I'm using version 1.6.0_05. I've tried running jucheck.exe. It tells me I've got the latest version installed.
Here is the code:
import java.lang.StringBuilder;
import java.util.Formatter;
public class UsingFormatter {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("usage: " +
"java format/UsingFormatter <format string>");
System.exit(0);
String format = args[0];
StringBuilder stringBuilder = new StringBuilder();
Formatter formatter = new Formatter(stringBuilder);
formatter.format("Pi is approximately " + format +
", and e is about " + format, Math.PI, Math.E);
System.out.println(stringBuilder);
}When I type javac UsingFormatter.java, I get:
UsingFormatter.java:1: cannot resolve symbol
symbol : class StringBuilder
location: package lang
import java.lang.StringBuilder;
^
UsingFormatter.java:2: cannot resolve symbol
symbol : class Formatter
location: package util
import java.util.Formatter;
^
UsingFormatter.java:14: cannot resolve symbol
symbol : class StringBuilder
location: class UsingFormatter
StringBuilder stringBuilder = new StringBuilder();
^
UsingFormatter.java:14: cannot resolve symbol
symbol : class StringBuilder
location: class UsingFormatter
StringBuilder stringBuilder = new StringBuilder();
^
UsingFormatter.java:15: cannot resolve symbol
symbol : class Formatter
location: class UsingFormatter
Formatter formatter = new Formatter(stringBuilder);
^
UsingFormatter.java:15: cannot resolve symbol
symbol : class Formatter
location: class UsingFormatter
Formatter formatter = new Formatter(stringBuilder);
^
6 errors
The compiler refuses to recognize the symbols StringBuilder and Formatter.
I have spent hours googling for an answer and trying every suggestion. Nothing works, not even the one about dropping the computer from the rooftop.
Ultimately, what I'm trying to accomplish (in a different program) is to use a text file as a form letter template and replace the %s placeholders with stings from my form object.
Any advice?
Edited by: javastudent_99 on Apr 3, 2008 1:48 PM -
Compile error - cannot resolve symbol
Hello,
I am trying this code although I get compile errors as stated.
import java.util.Scanner;
* Write a program that reads 10 numbers from the keyboard into
* an array and then prints the list of numbers
* Modify the above program so that it prints the numbers in reverse order
class Keyboard
public static void main (String[] argStrings)
System.out.println("Enter 10 numbers please");
Scanner scan = new Scanner(System.in);
int[] newArray = new int[10];
for(int i = 0; i < 10; i++)
newArray[i] = scan.nextInt();
System.out.println();
for(int i = 9; i > 0; i--)
System.out.print(newArray);
System.out.println();
I have googled for solutions but have had no luck or could not understand.
Please could someone explain what is going on.
CheersE:\Documents and Settings\John\Desktop\Computing\Programming\Weeks\Week11\Keyboard.java:1: cannot resolve symbol
symbol : class Scanner
location: package util
import java.util.Scanner;
^
E:\Documents and Settings\John\Desktop\Computing\Programming\Weeks\Week11\Keyboard.java:15: cannot resolve symbol
symbol : class Scanner
location: class Keyboard
Scanner scan = new Scanner(System.in);
^
E:\Documents and Settings\John\Desktop\Computing\Programming\Weeks\Week11\Keyboard.java:15: cannot resolve symbol
symbol : class Scanner
location: class Keyboard
Scanner scan = new Scanner(System.in);
^
3 errors
Tool completed with exit code 1
cheers -
JSP Compilation Problem - Cannot Resolve Symbol
I cannot see the problem. Maybe I am not sober at 2:30 am.
<%
Collection postBeans = ( Collection )request.getAttribute( "PostBeans" );
Iterator iterator = postBeans.iterator();
int i = 0;
while( iterator.hasNext() )
PostBean postBean = (PostBean)iterator.next();
i++;
String background;
if ( postBean.getParentPostID() == 0 )
background = "#FFCE9C";
else
if ( ( i%2 ) != 0 )
background = "#EEEEEE";
else
background = "#FFFFFF";
%>
<table width="95%" border="0" cellspacing="1" cellpadding="5" align="center" bgcolor="#999999">
<tr bgColor=<%=background%>>
</tr>
</table>I got compilation error: cannot resolve symbol
symbol: backgroundI put the variable 'background' outside the while loop. The 'cannot resolve symbol' problem is gone. But, I got another compilation error:
>
unexpected type
required: variable
found : value
out.write("\r\n }\r\n i++;\r\n if ( postBean.getParentPostID() == 0 ) \r\n {\r\n background = \"#FFCE9C\";\r\n }\r\n else \r\n {\r\n if ((i%2) != 0) \r\n {\r\n background = \"#EEEEEE\";\r\n } \r\n else \r\n {\r\n background = \"#FFFFFF\";\r\n }\r\n }\r\n%>\r\n");
The code looks like:
<%
String background;
Collection postBeans = ( Collection )request.getAttribute( "PostBeans" );
Iterator iterator = postBeans.iterator();
int i = 0;
while( iterator.hasNext() )
PostBean postBean = (PostBean)iterator.next();
i++;
if ( postBean.getParentPostID() == 0 )
background = "#FFCE9C";
else
if ( ( i%2 ) != 0 )
background = "#EEEEEE";
else
background = "#FFFFFF";
%>
<table width="95%" border="0" cellspacing="1" cellpadding="5" align="center" bgcolor="#999999">
<tr bgColor=<%=background%>>
</tr>
</table> -
When i try to use max() & pow() in jdbc i get error "cannot resolve symbol"
hi,
when i tried to use pow() & max() in my jdbc programme i got compilation error "cannot resolve symbol".
even i have imorted java.math
this is the sample.
pr1= (fy/(L*B*pow(10.0,-6.0))+((6*mx)/(L*B*B*pow(10.0,-6.0)))+((6*mz)/(B*L*L*pow(10.0,-6.0))));
all of above are double.
and with max();
pr=max(pr1,pr2);
all of above are double.
please help.
thanks in advance.
satishhi
Hartmut
thanks hartmut;
i am new in java so i have some problems, but thanks for helping me.
please help me again.
as i have already posted another probleme which i have with selecting 1000 rows 1 by 1 from a table & manipulate 1 by 1 on that and then store all manipulated row to another table.
when i tried to do so i am able to select only 600 rows and manipulate them & store them.
i did not get any exception or any error.
can this possible that microsoft access driver has not that much capacity to provide 1000 rows or it is problem with jdbc.
please help.
satish
thanks again. -
Error:cannot resolve Symbol class"name"
when I have compiled Bean class named SlBean which has primary class named pk, I recevied following error message(I compiled pk class without error) :
cannot resolve symbol
symbol : class pk
location: class SlBean
public pk ejbCreate(Sorry , its not classpath problem. You have to simply import the pk class if its in any package. I am assuming you have packaged your pk class with ejb jar file.
for eg. if your class is
package abc.xyz
public class pk
then in your bean class import
import abc.xyz.pk;
--Ashwani -
I am getting an error cannot resolve symbol variable?
I am trying to run a PdfFormGenerator.java file and am using the iText API, hence have included
the iText.jar file. When I compile the code I keep getting the following two errors:
cannot resolve symbol variable CLASS_LOCATION
cannot resolve symbol variable FORM_LOCATION
can anyone guide me what I may have done wrong.
Thanks,
ZubHi! To be more specific its these to line of the code is were I am going the errors:
private String classLocation = Constants.CLASS_LOCATION;
private String formLocation = Constants.FORM_LOCATION;Thanks -
Need help - method call error cannot resolve symbol
My code compiles fine but I continue to receive a method call error "cannot resolve symbol - variable superman" - can't figure out why. Here is my code:
public static String caesar(String message, int shift)
{ [b]String result = "";
for(int i = 0; i < message.length(); ++i)
{ [b]char newChar = message.charAt(i + shift);
result += newChar;
return result.toUpperCase();
I entered "superman" for message and "3" for the shift. Can someone please help? Thanks!Your post worked great - especially since it made me realize I was going about it all wrong! I was attempting to convert "superman" to "vxshupdq" - basically a cipher shift starting at index 0 and shifting it 3 character values which would result in s changing to v. I restructured my code:
public static String caesar(String message, int shift)
{ [b]String result = "";
for(int i = 0; i < message.length(); ++i)
{ [b]char newChar = message.charAt(i);
result += (newChar + shift) % message.length();
return result.toUpperCase();
But it's displaying the result as a "60305041". How can I get it to display the actual characters? -
Compiler error: "cannot find symbol" - constructor
Dear all,
I keep getting the compiler error "cannot find symbol" - constructor AWTEvent() for the following class. It's supposed to extend AWTEvent to give me my own event to be fired. What could be wrong?
import java.awt.*;
import java.awt.event.*;
public class MyButtonEvent extends AWTEvent
public MyButtonEvent()
}Thanks a lot!
NWhen you do this
public MyButtonEvent()
}you are implicitly calling the super class constructor with no parameters
That is:
AWTEvent();
you can think of it as
public MyButtonEvent()
AWTEvent(); // <-- automatically generated for you
//the rest of your stuff
}the problem is that AWTEvent has no such constructor, so you need to explicitly put another constructor in your constructor as the first statement. This other constructor has to be one that exists in AWTEvent. -
Class error - cannot resolve symbol "MyDocumentListener"
Hello,
this is a groaner I'm sure, but I don't see the problem.
Newbie-itis probably ...
I'm not concerned with what the class does, but it would be nice for the silly thing to compile!
What the heck am I missing for "MyDocumentListener" ?
C:\divelog>javac -classpath C:\ CenterPanel.java
CenterPanel.java:53: cannot resolve symbol
symbol : class MyDocumentListener
location: class divelog.CenterPanel
MyDocumentListener myDocumentListener = new MyDocumentListener(); // define the listener class
^
CenterPanel.java:53: cannot resolve symbol
symbol : class MyDocumentListener
location: class divelog.CenterPanel
MyDocumentListener myDocumentListener = new MyDocumentListener(); // define the listener class
^
2 errors
package divelog;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.lang.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.filechooser.*;
import javax.swing.text.*;
public class CenterPanel extends JPanel implements ActionListener
{ // Opens class
static private final String newline = "\n";
private JTextArea comments;
private JScrollPane scrollpane;
private JButton saveButton, openButton;
private JLabel whiteshark;
private Box box;
private BufferedReader br ;
private String str;
private JTextArea instruct;
private File defaultDirectory = new File("C://divelog");
private File fileDirectory = null;
private File currentFile= null;
public CenterPanel()
{ // open constructor CenterPanel
setBackground(Color.white);
comments = new JTextArea("Enter comments, such as " +
"location, water conditions, sea life you observed," +
" and problems you may have encountered.", 15, 10);
comments.setLineWrap(true);
comments.setWrapStyleWord(true);
comments.setEditable(true);
comments.setFont(new Font("Times-Roman", Font.PLAIN, 14));
// add a document listener for changes to the text,
// query before opening a new file to decide if we need to save changes.
MyDocumentListener myDocumentListener = new MyDocumentListener(); // define the listener class
comments.getDocument().addDocumentListener(myDocumentListener); // create the reference for the class
// ------ Document listener class -----------
class MyDocumentListener implements DocumentListener {
public void insertUpdate(DocumentEvent e) {
Calculate(e);
public void removeUpdate(DocumentEvent e) {
Calculate(e);
public void changedUpdate(DocumentEvent e) {
private void Calculate(DocumentEvent e) {
// do something here
scrollpane = new JScrollPane(comments);
scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
saveButton = new JButton("Save Comments", new ImageIcon("images/Save16.gif"));
saveButton.addActionListener( this );
saveButton.setToolTipText("Click this button to save the current file.");
openButton = new JButton("Open File...", new ImageIcon("images/Open16.gif"));
openButton.addActionListener( this );
openButton.setToolTipText("Click this button to open a file.");
whiteshark = new JLabel("", new ImageIcon("images/gwhite.gif"), JLabel.CENTER);
Box boxH;
boxH = Box.createHorizontalBox();
boxH.add(openButton);
boxH.add(Box.createHorizontalStrut(15));
boxH.add(saveButton);
box = Box.createVerticalBox();
box.add(scrollpane);
box.add(Box.createVerticalStrut(10));
box.add(boxH);
box.add(Box.createVerticalStrut(15));
box.add(whiteshark);
add(box);
} // closes constructor CenterPanel
public void actionPerformed( ActionEvent evt )
{ // open method actionPerformed
JFileChooser jfc = new JFileChooser();
// these do not work !!
// -- set the file types to view --
// ExtensionFileFilter filter = new ExtensionFileFilter();
// FileFilter filter = new FileFilter();
//filter.addExtension("java");
//filter.addExtension("txt");
//filter.setDescription("Text & Java Files");
//jfc.setFileFilter(filter);
//Add a custom file filter and disable the default "Accept All" file filter.
jfc.addChoosableFileFilter(new JTFilter());
jfc.setAcceptAllFileFilterUsed(false);
// -- open the default directory --
// public void setCurrentDirectory(File dir)
// jfc.setCurrentDirectory(new File("C://divelog"));
jfc.setCurrentDirectory(defaultDirectory);
jfc.setSize(400, 300);
jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
Container parent = saveButton.getParent();
//========================= Test Button Actions ================================
//========================= Open Button ================================
if (evt.getSource() == openButton)
int choice = jfc.showOpenDialog(CenterPanel.this);
File file = jfc.getSelectedFile();
/* a: */
if (file != null && choice == JFileChooser.APPROVE_OPTION)
String filename = jfc.getSelectedFile().getAbsolutePath();
// -- compare the currentFile to the file chosen, alert of loosing any changes to currentFile --
// If (currentFile != filename)
// -- get the current directory name -------
// public File getCurrentDirectory( );
File f=new File(System.getProperty("user.dir"));
fileDirectory = jfc.getCurrentDirectory();
// -- remember the last directory used --
if (defaultDirectory != fileDirectory)
{defaultDirectory = fileDirectory;}
try
{ //opens try
comments.getLineCount( );
// -- clear the old data before importing the new file --
comments.selectAll();
comments.replaceSelection("");
// -- get the new data ---
br = new BufferedReader (new FileReader(file));
while ((str = br.readLine()) != null)
{//opens while
comments.append(str);
} //closes while
} // close try
catch (IOException ioe)
{ // open catch
comments.append(newline +"Open command not successful:" + ioe + newline);
} // close catch
// ---- display the values of the directory variables -----------------------
comments.append(
newline + "The f directory variable contains: " + f +
newline + "The fileDirectory variable contains: " + fileDirectory +
newline + "The defaultDirectory variable contains: " + defaultDirectory );
else
comments.append("Open command cancelled by user." + newline);
} //close if statement /* a: */
//========================= Save Button ================================
} else if (evt.getSource() == saveButton)
int choice = jfc.showSaveDialog(CenterPanel.this);
if (choice == JFileChooser.APPROVE_OPTION)
File fileName = jfc.getSelectedFile();
// -- get the current directory name -------
// public File getCurrentDirectory( );
File f=new File(System.getProperty("user.dir"));
fileDirectory = jfc.getCurrentDirectory();
// -- remember the last directory used --
if (defaultDirectory != fileDirectory)
{defaultDirectory = fileDirectory;}
//check for existing files. Warn users & ask if they want to overwrite
for(int i = 0; i < fileName.length(); i ++) {
File tmp = null;
tmp = (fileName);
if (tmp.exists()) // display pop-up alert
//public static int showConfirmDialog( Component parentComponent,
// Object message,
// String title,
// int optionType,
// int messageType,
// Icon icon);
int confirm = JOptionPane.showConfirmDialog(null,
fileName + " already exists on " + fileDirectory
+ "\n \nContinue?", // msg
"Warning! Overwrite File!", // title
JOptionPane.OK_CANCEL_OPTION, // buttons displayed
// JOptionPane.ERROR_MESSAGE
// JOptionPane.INFORMATION_MESSAGE
// JOptionPane.PLAIN_MESSAGE
// JOptionPane.QUESTION_MESSAGE
JOptionPane.WARNING_MESSAGE,
null);
if (confirm != JOptionPane.YES_OPTION)
{ //user cancels the file overwrite.
try {
jfc.cancelSelection();
break;
catch(Exception e) {}
// ----- Save the file if everything is OK ----------------------------
try
{ // opens try
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
bw.write(comments.getText());
bw.flush();
bw.close();
comments.append( newline + newline + "Saving: " + fileName.getName() + "." + newline);
break;
} // closes try
catch (IOException ioe)
{ // open catch
comments.append(newline +"Save command unsuccessful:" + ioe + newline);
} // close catch
} // if exists
} //close for loop
else
comments.append("Save command cancelled by user." + newline);
} // end-if save button
} // close method actionPerformed
} //close constructor CenterPanel
} // Closes class CenterPanelThere is no way to be able to see MyDocumentListener class in the way you wrote. The reason is because MyDocumentListener class inside the constructor itself. MyDocumentListener class is an inner class, not suppose to be inside a constructor or a method. What you need to do is simple thing, just move it from inside the constructor and place it between two methods.
that's all folks
Qusay -
Error: Cannot Resolve symbol
Hi i have written this program but it is not compling properly. i do not know what to do to sort it. here is the code:
import java.sql.*;
import java.io.DataInputStream;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Phase1 extends JFrame implements ActionListener, MouseListener
//Create Buttons and Text areas etc for the GUI itself
JButton add, current, delete, order, all, exit;
JTextField textStockCode, textStockDesc, textCurrentLevel, textReorderLevel, textPrice;
JTextArea textarea;
JScrollPane pane1;
JLabel labelStockCode, labelStockDesc, labelCurrentLevel, labelReorderLevel, labelPrice, labelTextArea;
String stockCode, stockDesc, currentLevel, reorderLevel, price;
JLabel welcome;
//Setup database connections and statements for later use
Connection db_connection;
Statement db_statement;
public Phase1()
//Display a welcome message before loading system onto the screen
JOptionPane.showMessageDialog(null, "Welcome to the Stock Control System");
//set up the GUI environment to use a grid layout
Container content=this.getContentPane();
content.setLayout(new GridLayout(3,6));
//Inititlise buttons
add=new JButton("Add");
add.addActionListener(this);
current=new JButton("Show Current Level");
current.addActionListener(this);
delete=new JButton("Delete");
delete.addActionListener(this);
order=new JButton("Place Order");
order.addActionListener(this);
all = new JButton("Show All Entries");
all.addActionListener(this);
exit = new JButton("Exit");
exit.addActionListener(this);
//Add Buttons to the layout
content.add(add);
content.add(current);
content.add(delete);
content.add(order);
content.add(all);
content.add(exit);
//Initialise text fields for inputting data to the database and
//Add mouse listeners to clear the boxs on a click event
textStockCode = new JTextField("");
textStockCode.addMouseListener(this);
textStockDesc = new JTextField("");
textStockDesc.addMouseListener(this);
textCurrentLevel = new JTextField("");
textCurrentLevel.addMouseListener(this);
textReorderLevel = new JTextField("");
textReorderLevel.addMouseListener(this);
textPrice = new JTextField("");
textPrice.addMouseListener(this);
//Initialise the labels to label the Text Fields
labelStockCode = new JLabel("Stock Code");
labelStockDesc = new JLabel("Stock Description");
labelCurrentLevel = new JLabel("Current Level");
labelReorderLevel = new JLabel("Re-Order Level");
labelPrice = new JLabel("Price");
labelTextArea = new JLabel("All Objects");
//Add Text fields and labels to the GUI
content.add(labelStockCode);
content.add(textStockCode);
content.add(labelStockDesc);
content.add(textStockDesc);
content.add(labelCurrentLevel);
content.add(textCurrentLevel);
content.add(labelReorderLevel);
content.add(textReorderLevel);
content.add(labelPrice);
content.add(textPrice);
content.add(labelTextArea);
//Create a text area with scroll bar for showing Entries in the text area
textarea=new JTextArea();
textarea.setRows(6);
pane1=new JScrollPane(textarea);
content.add(pane1);
//Try to connect to the database through ODBC
try
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
//Create a URL that identifies database
String url = "jdbc:odbc:" + "stock";
//Now attempt to create a database connection
//First parameter data source, second parameter user name, third paramater
//password, the last two paramaters may be entered as "" if no username or
//pasword is used
db_connection = DriverManager.getConnection(url, "demo","");
//Create a statement to send SQL
db_statement = db_connection.createStatement();
catch (Exception ce){} //driver not found
//action performed method for button click events
public void actionPerformed(ActionEvent ev)
if(ev.getSource()==add) //If add button clicked
try
add(); //Run add() method
catch(Exception e){}
if(ev.getSource()==current)
{ //If Show Current Level Button Clicked
try
current(); //Run current() method
catch(Exception e){}
if(ev.getSource()==delete)
{ //If Show Delete Button Clicked
try
delete(); //Run delete() method
catch(Exception e){}
if(ev.getSource()==order) //If Show Order Button Clicked
try
order(); //Run order() method
catch(Exception e){}
if(ev.getSource()==all) //If Show Show All Button Clicked
try
all(); //Run all() method
catch(Exception e){}
if(ev.getSource()==exit) //If Show Exit Button Clicked
try{
exit(); //Run exit() method
catch(Exception e){}
public void add() throws Exception //add a new stock item
stockCode = textStockCode.getText();
stockDesc = textStockDesc.getText();
currentLevel = textCurrentLevel.getText();
reorderLevel = textReorderLevel.getText();
price = textPrice.getText();
if(stockCode.equals(""))
JOptionPane.showMessageDialog(null,"Ensure Stock Code is filled out");
if(stockDesc.equals(""))
JOptionPane.showMessageDialog(null,"Ensure Description is filled out");
if(price.equals(""))
JOptionPane.showMessageDialog(null,"Ensure price is filled out");
if(currentLevel.equals(""))
JOptionPane.showMessageDialog(null,"Ensure Current Level is filled out");
if(reorderLevel.equals(""))
JOptionPane.showMessageDialog(null,"Ensure Re-Order Level is filled out");
else
//Add item to database with variables set from text fields
db_statement.executeUpdate("INSERT INTO stock VALUES
('"+stockCode+"','"+stockDesc+"','"+currentLevel+"','"+reorderLevel+"','"+price+"')");
public void current() throws Exception //check a current stock level
if(textStockCode.getText().equals(""))//if no stockcode has been entered
JOptionPane.showMessageDialog(null,"Enter a Stock Code.");
else
ResultSet resultcurrent = db_statement.executeQuery("SELECT * FROM stock WHERE StockCode = '"+textStockCode.getText()+"'");
textarea.setText("");
if(resultcurrent.next())
do
textarea.setText("Stock Code: "+resultcurrent.getString("StockCode")+"\nDescription:
"+resultcurrent.getString("StockDescription")+"\nCurrent Level: "+resultcurrent.getInt("CurrentLevel")+"\nRe-Order Level:
"+resultcurrent.getInt("ReorderLevel")+"\nPrice: "+resultcurrent.getFloat("Price"));
while(resultcurrent.next());
else
//Display Current Stock Item (selected from StockCode Text field in the scrollable text area
JOptionPane.showMessageDialog(null,"Not a valid Stock Code");
public void delete() throws Exception //delete a current stock item
if(textStockCode.getText().equals("")) //Check there is a stock code entered
JOptionPane.showMessageDialog(null,"Enter a Stock Code.");
else
//Delete Item from database where Stock Code is what is in Stock Code Text Field
db_statement.executeUpdate("DELETE * FROM stock WHERE StockCode='"+textStockCode.getText()+"'");
public void order() throws Exception //check price for an order
if(textStockCode.getText().equals("")) //Check there is a stock code entered
JOptionPane.showMessageDialog(null,"Enter a Stock Code.");
else
//Set some variables to aid ordering
float price = 0;
int currentlevel = 0;
int newlevel = 0;
int reorder = 0;
String StockCode = textStockCode.getText();
//Post a message asking how many to order
String str_quantity = JOptionPane.showInputDialog(null,"Enter Quantity: ","Adder",JOptionPane.PLAIN_MESSAGE);
int quantity = Integer.parseInt(str_quantity);
//Get details from database for current item
ResultSet resultorder = db_statement.executeQuery("SELECT * FROM stock WHERE StockCode='"+StockCode+"'");
//Set variables from database to aid ordering
while (resultorder.next())
price = resultorder.getFloat("Price");
currentlevel = (resultorder.getInt("CurrentLevel"));
reorder = (resultorder.getInt("ReorderLevel"));
//Set the new level to update the database
newlevel = currentlevel - quantity;
//calculate the total price of the order
float total = price * quantity;
//If the stock quantity is 0
if(quantity == 0)
//Display a message saying there are none left in stock
JOptionPane.showMessageDialog(null,"No Stock left for this item");
//Otherwise check that the quantity ordered is more than what is lewft in stock
else if(quantity > currentlevel)
//If ordered too many display a message saying so
JOptionPane.showMessageDialog(null,"Not enough in stock, order less");
else
//Otherwise Display the total in a message box
JOptionPane.showMessageDialog(null,"Total is: "+total);
//then update the database with new values
db_statement.executeUpdate("UPDATE Stock SET CurrentLevel="+newlevel+" WHERE StockCode='"+StockCode+"'");
//Check if the new level is 0
if(newlevel == 0)
//If new level IS 0, send a message to screen saying so
JOptionPane.showMessageDialog(null,"There is now no Stock left.");
else
//otherwise if the newlevel of stock is the same as the reorder level
if(newlevel == reorder)
// display a message to say so
JOptionPane.showMessageDialog(null,"You are now at the re-order level, Get some more of this item in
stock.");
//Otherwise if the new level is lower than the reorder level,
if(newlevel < reorder)
//Display a message saying new level is below reorder level so get some more stock
JOptionPane.showMessageDialog(null,"You are now below the reorder level. Get some more of this item in
stock.");
public void all() throws Exception //show all stock items and details
//Get everthing from the database
ResultSet resultall = db_statement.executeQuery("SELECT * FROM Stock");
textarea.setText("");
while (resultall.next())
//Display all items of stock in the Text Area one after the other
textarea.setText(textarea.getText()+"Stock Code: "+resultall.getString("StockCode")+"\nDescription:
"+resultall.getString("StockDescription")+"\nCurrent Level: "+resultall.getInt("CurrentLevel")+"\nRe-Order Level:
"+resultall.getInt("ReorderLevel")+"\nPrice: "+resultall.getFloat("Price")+"\n\n");
public void exit() throws Exception //exit
//Cause the system to close the window, exiting.
db_connection.commit();
db_connection.close();
System.exit(0);
public static void main(String args[])
//Initialise a frame
JDBCFrame win=new JDBCFrame();
//Set the size to 800 pixels wide and 350 pixels high
win.setSize(900,350);
//Set the window as visible
win.setVisible(true);
win.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
//Mouse Listener Commands
public void mousePressed(MouseEvent evt)
if (evt.getSource()==textStockCode)
//Clear the Stock Code text field on clickin on it
textStockCode.setText("");
else if (evt.getSource()==textStockDesc)
//Clear the Stock Description text field on clickin on it
textStockDesc.setText("");
else if (evt.getSource()==textCurrentLevel)
textCurrentLevel.setText("");
//Clear the Current Level text field on clickin on it
else if (evt.getSource()==textReorderLevel)
textReorderLevel.setText("");
//Clear the Re-Order Level text field on clickin on it
else if (evt.getSource()==textPrice)
textPrice.setText("");
//Clear the Price text field on clickin on it
public void mouseReleased(MouseEvent evt){}
public void mouseClicked(MouseEvent evt){}
public void mouseEntered(MouseEvent evt){}
public void mouseExited(MouseEvent evt){}
}And this is the error that i get when compiling:
Phase1.java:355: cannot resolve symbol
symbol : class JDBCFrame
location: class Phase1
JDBCFrame win=new JDBCFrame();
^
Phase1.java:355: cannot resolve symbol
symbol : class JDBCFrame
location: class Phase1
JDBCFrame win=new JDBCFrame();Thanks for any help you can give meThe error is very clear here
Phase1.java:355: cannot resolve symbolsymbol : class JDBCFramelocation: class Phase1 JDBCFrame win=new JDBCFrame();
Where is this class JDBCFrame()?
Import that package or class -
Compilation problem (cannot resolve symbol)
I have searched the Forums for "cannot resolve symbol" and as usual, many posts with no answers or just advise that noone ever comes back to say works. I am trying to compile this code:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.*;
import org.acme.*;
public class HelloOpenEJB extends HttpServlet {
String factory = "org.openejb.client.LocalInitialContextFactory";
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
PrintWriter out = response.getWriter();
try{
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, factory );
InitialContext ctx = new InitialContext( p );
//Lookup the bean using it's deployment id
Object obj = ctx.lookup("/Hello");
HelloHome ejbHome = (HelloHome) obj;
//Use the HelloHome to create a HelloObject
HelloHome ejbHome = (HelloHome)
PortableRemoteObject.narrow(obj, HelloHome.class);
//The part we've all been wainting for...
out.println("<html>");
out.println("<body>");
out.println("<head>");
out.println("<title>Hello World!</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>"+ ejbObject.sayHello() +"</h1>");
out.println("</body>");
out.println("</html>");
} catch (Exception e){
response.setContentType("text/plain");
e.printStackTrace(out);
I'm running this on a Linux box. When I compile, I get this:
HelloOpenEJB.java:28: ejbHome is already defined in doGet(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
HelloHome ejbHome = (HelloHome)
^
HelloOpenEJB.java:29: cannot resolve symbol
symbol : variable PortableRemoteObject
location: class HelloOpenEJB
PortableRemoteObject.narrow(obj, HelloHome.class);
^
HelloOpenEJB.java:38: cannot resolve symbol
symbol : variable ejbObject
location: class HelloOpenEJB
out.println(""+ ejbObject.sayHello() +"");
^
3 errors
I don't know why any of these errors are occuring, besides the obvious responses given back from javac, so can someone help? Thanks, JeremyThe error message "x already defined in y" means that you're trying to use a name that already exists in the current scope. In your case you have:
HelloHome ejbHome = (HelloHome) obj;
//Use the HelloHome to create a HelloObject
HelloHome ejbHome = (HelloHome)
PortableRemoteObject.narrow(obj, HelloHome.class);Here you are trying to declare two instances of HelloHome with the same name.
The reason that you would get "cannot resolve symbol" is that you are trying to access a variable or class that you haven't declared or imported. -
3 graphic errors- Cannot resolve Symbols
I am looking for help to resolve 3 errors that I don't understand and I am hoping someone can take the time to point me in the right directions.
The errors occur while setting the forground color, trying to repaint and trying to draw a rectangle.
Here are the errors from the compiler:
Worm.java [42:1] cannot resolve symbol
symbol : method setForeground (java.awt.Color)
location: class Worm
setForeground(Color.RED);
^
Worm.java [49:1] cannot resolve symbol
symbol : method repaint ()
location: class Worm
repaint();
^
Worm.java [56:1] cannot resolve symbol
symbol : method drawRectangle (int,java.awt.Rectangle,int,int)
location: class java.awt.Graphics
g.drawRectangle(rec.x, rec[i], rec[i].height, rec[i].width );
^
3 errors
Errors compiling Worm.java.
The code follows:
Thanks for any assistance inadvance
WBR
import java.awt.*;
import java.awt.Graphics.*;
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
import java.awt.Rectangle.*;
import java.io.*;
import java.util.*;
class WormFrame extends JFrame{
public WormFrame(){
setTitle("CenteredFrame");
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
int screenHeight = d.height;
int screenWidth = d.width;
setSize(screenWidth / 2, screenHeight / 2);
setLocation(screenWidth / 4, screenHeight / 4);
public class Worm{
Rectangle rec[];
private Worm(){
Rectangle rec[] = new Rectangle [25];
int x = 25;
int y = 25;
for(int i = 0; i < rec.length; i++ ){
rec.x = x++;
rec[i].y = y++;
rec[i].height = 1;
rec[i].width = 1;
private void wormDraw( ){
setForeground(Color.RED); // Error 1
for(int a = 1; a < 20; a++){
for(int i = 1; i < rec.length; i++ ){
rec[i].x += 1;
rec[i].y += 1;
repaint(); // Error 2
public void paint(Graphics g) {
System.out.println("paint : " + new Date( ) );
// Draw dots
for(int i = 0; i < rec.length; i++ ){
g.drawRectangle(rec[i].x, rec[i], rec[i].height, rec[i].width ); // Error 3
public static void main(String[] args){
JFrame frame = new WormFrame();
frame.show();
Worm w = new Worm();
w.wormDraw();Hello! This works...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
public class Worm extends JFrame
Rectangle rec[];
public Worm()
setTitle("CenteredFrame");
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
int screenHeight = d.height;
int screenWidth = d.width;
setSize(screenWidth / 2, screenHeight / 2);
setLocation(screenWidth / 4, screenHeight / 4);
setVisible(true);
rec = new Rectangle [25];
int x = 25;
int y = 25;
for(int i = 0; i < rec.length; i++ )
System.out.println("Creating rec " + i);
rec[i] = new Rectangle();
rec.x = x++;
rec[i].y = y++;
rec[i].height = 1;
rec[i].width = 1;
public void wormDraw( )
setForeground(Color.RED);
for(int a = 1; a < 20; a++)
for(int i = 1; i < rec.length; i++ )
System.out.println("Drawing rec " + i);
rec[i].x += 1;
rec[i].y += 1;
System.out.println("Calling paint");
repaint();
validate();
System.out.println("Done");
public void paint(Graphics g)
System.out.println("paint : " + new Date( ) );
for(int i = 0; i < rec.length; i++ )
g.fillRect(rec[i].x, rec[i].y, rec[i].height, rec[i].width);
public static void main(String[] args)
new Worm().wormDraw();
regards,
Liam
Maybe you are looking for
-
AUC Asset not getting created when Internal Order is created
Dear Experts, While Creating the internal order ( Object Class - Investment Measure) AuC (Asset Under Construction) not getting created automaticall . Note Investment profile is already there in the order. Following steps below are configured - 1. De
-
hi there i wanna create a exe file so i am trying to use jar file. I am new at creating jar files, my application has a main file and other java files, i am using other java files in my main file my concern is can i create a jar file including all th
-
Flash Builder - No Code Hinting For New Flash Professional Project??
I had been using flash builder as an as3 editor and compiling from flash builder. The Flash Professional Project in Flash Builder seems perfect. It will give me the flexibility to compile from Flash Professional, or compile from the flex sdk, use bre
-
Dreamweaver CS3 Training from the Source
I am working through your book, with the intention of using it as a textbook this coming fall semester in my high school web design class. (Have used previous versions of this book before with great success.) This is my first experience with XML/Spry
-
Hi guys ...i have a problem im on BO 3.1 SP3 and i want to know how show all rows in a single page...im trying using the Quick Display mode and changing the max Rows but when i reach 1500 or 2000 appears that is the maximum and if i set more that tha