Try/catch and 'cannot resolve symbol'
I am relatively new to java programming and something has me puzzled...
Why do I get a 'cannot resolve symbol' message when I include a variable definition in a try/catch section. When I put it/them before the 'try' statement it compiles as expected. How are statements inside a try compiled differently than those outside?
try {
StringBuffer pageBuffer = new StringBuffer();
String inputLine;
BufferedReader in = new BufferedReader(
new InputStreamReader( theURL.openStream() ) );
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
pageBuffer.append(inputLine);
in.close();
} catch (Exception ignored) {}C:\Projects\WebExplorer\PageVisitor.java:142: cannot resolve symbol
symbol : variable pageBuffer
location: class PageVisitor
return pageBuffer.toString();
Paul
A try block is just like any other block delimited by {...} in that all variables declared inside it are local to that block. I.e. they are not visible or usable anywhere outside it. Your pageBuffer variable, for example, is a local variable that can only be used inside the try-block in which it is declared.
Your obvious solution, knowing that, is to declare the variables outside the try and catch blocks. Remember to initialize them (even to null), otherwise the compiler will complain about variables that may not have been initialized.
Similar Messages
-
Cannot find package error and cannot resolve symbol error
Hi
I have a file Assignment.java in C:\TIJCode\c03 folder. But this file belongs to the default package. This file imports a package com.bruceeckel.simpletest which is in C:\TIJCode\ folder. Now this package has a file named Test.java which accesses a few more files fromt he same package.
I set the classpath to C:\TIJCode. When i try to run the Assignment file I get an error saying package com.bruceeckel.simpletest cannot be found and cannot resolve symbol error. symbol: Test Class: Assignment.
The files in com.bruceeckel.simpletest package were not compiled. So I first tried to do that. But I get a cannot resolve symbol error while trying to compile a file NumOfLinesException which inherits SImpleTestException file. The exact error message is
NumOfLinesException.java : 7 : cannot resolve symbol
symbol : class SimpleTestException
location : class com.bruceeckel.simpletest.NumOfLinesException extends SimpleTestException
The exact code in each of above mentioned files is
//: c03:Assignment.java
// Assignment with objects is a bit tricky.
// From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
// www.BruceEckel.com. See copyright notice in CopyRight.txt.
import com.bruceeckel.simpletest.*;
class Number {
int i;
public class Assignment {
static Test monitor = new Test();
public static void main(String[] args) {
Number n1 = new Number();
Number n2 = new Number();
n1.i = 9;
n2.i = 47;
System.out.println("1: n1.i: " + n1.i +
", n2.i: " + n2.i);
n1 = n2;
System.out.println("2: n1.i: " + n1.i +
", n2.i: " + n2.i);
n1.i = 27;
System.out.println("3: n1.i: " + n1.i +
", n2.i: " + n2.i);
monitor.expect(new String[] {
"1: n1.i: 9, n2.i: 47",
"2: n1.i: 47, n2.i: 47",
"3: n1.i: 27, n2.i: 27"
} ///:~
//: com:bruceeckel:simpletest:SimpleTestException.java
// From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
// www.BruceEckel.com. See copyright notice in CopyRight.txt.
package com.bruceeckel.simpletest;
public class SimpleTestException extends RuntimeException {
public SimpleTestException(String msg) {
super(msg);
} ///:~
//: com:bruceeckel:simpletest:NumOfLinesException.java
// From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
// www.BruceEckel.com. See copyright notice in CopyRight.txt.
package com.bruceeckel.simpletest;
public class NumOfLinesException extends SimpleTestException {
public NumOfLinesException(int exp, int out) {
super("Number of lines of output and "
+ "expected output did not match.\n" +
"expected: <" + exp + ">\n" +
"output: <" + out + "> lines)");
} ///:~
//: com:bruceeckel:simpletest:Test.java
// Simple utility for testing program output. Intercepts
// System.out to print both to the console and a buffer.
// From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
// www.BruceEckel.com. See copyright notice in CopyRight.txt.
package com.bruceeckel.simpletest;
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class Test {
// Bit-shifted so they can be added together:
public static final int
EXACT = 1 << 0, // Lines must match exactly
AT_LEAST = 1 << 1, // Must be at least these lines
IGNORE_ORDER = 1 << 2, // Ignore line order
WAIT = 1 << 3; // Delay until all lines are output
private String className;
private TestStream testStream;
public Test() {
// Discover the name of the class this
// object was created within:
className =
new Throwable().getStackTrace()[1].getClassName();
testStream = new TestStream(className);
public static List fileToList(String fname) {
ArrayList list = new ArrayList();
try {
BufferedReader in =
new BufferedReader(new FileReader(fname));
try {
String line;
while((line = in.readLine()) != null) {
if(fname.endsWith(".txt"))
list.add(line);
else
list.add(new TestExpression(line));
} finally {
in.close();
} catch (IOException e) {
throw new RuntimeException(e);
return list;
public static List arrayToList(Object[] array) {
List l = new ArrayList();
for(int i = 0; i < array.length; i++) {
if(array[i] instanceof TestExpression) {
TestExpression re = (TestExpression)array;
for(int j = 0; j < re.getNumber(); j++)
l.add(re);
} else {
l.add(new TestExpression(array[i].toString()));
return l;
public void expect(Object[] exp, int flags) {
if((flags & WAIT) != 0)
while(testStream.numOfLines < exp.length) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
List output = fileToList(className + "Output.txt");
if((flags & IGNORE_ORDER) == IGNORE_ORDER)
OutputVerifier.verifyIgnoreOrder(output, exp);
else if((flags & AT_LEAST) == AT_LEAST)
OutputVerifier.verifyAtLeast(output,
arrayToList(exp));
else
OutputVerifier.verify(output, arrayToList(exp));
// Clean up the output file - see c06:Detergent.java
testStream.openOutputFile();
public void expect(Object[] expected) {
expect(expected, EXACT);
public void expect(Object[] expectFirst,
String fname, int flags) {
List expected = fileToList(fname);
for(int i = 0; i < expectFirst.length; i++)
expected.add(i, expectFirst[i]);
expect(expected.toArray(), flags);
public void expect(Object[] expectFirst, String fname) {
expect(expectFirst, fname, EXACT);
public void expect(String fname) {
expect(new Object[] {}, fname, EXACT);
} ///:~What do you have in the C:\TIJCode\ directory? Does the directory structure mimic the package structure for the stuff you're importing?
-
IntValue - ")" expected and Cannot Resolve Symbol
I used intValue to convert an Integer to primitive (see below) and ran into syntax errors.
LogDataBean lb = new LogDataBean();
lb.setLog_time( ( String )row.get( "LOG_TIME" ) );
lb.setLog_pid( intValue( Integer )row.get( "LOG_PID" )); //where syntax error occur
lb.setLog_user( ( String )row.get( "LOG_USER" ) );the row.get( "LOG_PID" ) gets the value of the column "LOG_PID" from a database table and returns an object. Therefore, I first cast the object to Integer and then try to use the intValue to convert it to a primitive int.
But, the statement resulted in compilation error: ")" expected.
When I modified the statement a little bit by adding a pair of parenthesis:
lb.setLog_pid( intValue( ( Integer )row.get( "LOG_PID" ) ) ); //where syntax error occurI got "Cannot Resolve Symbol: intValue". I have import java.lang.Integer in the beginning of the class.Integer.parseInt(row.get( "LOG_PID" ))
I'm assuming thats what you want to. Although you syntax is terribly wrong. Have a look at some tutorials. -
Missing method body and cannot resolve symbol
I keep getting these two errors when trying to compile. I know that I need to call my fibonacci and factorial functions from the main function. Is this why I am getting the missing method body error? How do I correct this?
Am I getting the cannot resolve symbol because I have to set the num and fact to equal something?
Thanks
public class Firstassignment
public static void main(String[]args)
System.out.println();
public static void fibonacci(String[]args);
int even=1;
int odd=1;
while (odd<=100);
System.out.println(even);
int temp = even;
even = odd;
odd = odd + temp;
public static void factorial (String[]args);
for (int count=1;
count<=num;
count++);
fact = fact * count;
outputbox.printLine("Factorial of" + num + "is" + fact);Hey... :o)
the problem is that you've put semicolons at the end of the function signature, like this:
public static void fibonacci(String[]args);
}that should happen only when the function is abstract... so ur function should actually look like this:
public static void fibonacci(String[]args)
}also, i think you've missed out on the declarations (like what are fact and num??).... -
Help.. incompatiable type and cannot resolve symbol error...
I have this class Box
class Box{
private int width;
private int height;
private int depth;
private int BoxCounter;
public void click()
BoxCounter = 0;
}and in my main code, I'm calling it via
private Box arrBox[];All this goes fine until I try to place code in to make array empty upon a selected action by
if (color == blue) {arrBox = new Box();}Here I'm getting the error saying that its an incompatible type... it says I have Box but it requires class Box[]...(the ^ pointing at the word "new")
also, I have this
public void button()
arrBox.click()
}This returns the unable to resolve symbol error (the ^ points at the dot).... I tried changing things around but the problem persists, can someone point out where I hv gone wrong?
Many thanksprivate Box arrBox[];The line above does not create an array, it only declares that the variable arrBox can refernce an array of type Box. Arrays are objects just like Box - you need a new Box[10], for example, to create the array.
if (color == blue) {arrBox = new Box();}
Here I'm getting the error saying that its an
incompatible type... it says I have Box but it
requires class Box[]...(the ^ pointing at the word
"new")As previously stated, arrBox is a reference to an array of Box, not an object instance of Box.
A lot of your trouble can be resolved by understanding how arrays work in java. Try here.
http://java.sun.com/docs/books/tutorial/java/data/arrays.html
You must create an array similar to creating any object. Next, you must create objects to go inside the array. It's difficult without knowing the rest of your code, but here goes.
private Box[] arrBox = new Box[10];
for(int index=0;index<arrBox.length;index++) {
int color = getColor(index); //I'm making this up
if(color == blue) arrBox[index] = new Box();
}The above code will create a new Box for any index where the color is blue. The indices where the color isn't blue are equal to null. -
Try/catch issue - "cannot find symbol - class InputMismatchExeption"
I'm still learning try/catch but from what i've read online and in the class library it looks right...i'm not sure why it won't compile.
try {
do {
System.out.print("Enter command (1-5): ");
selection = scan.nextInt();
if (selection < 1 || selection > 5) {
System.out.print("Illegal command number.");
System.out.println("The available commands are:");
System.out.println("\t1. Add new entry to the address book.");
System.out.println("\t2. Delete existing entry from address book entries.");
System.out.println("\t3. Print out all address book entries.");
System.out.println("\t4. Search records for a certain pattern.");
System.out.println("\t5. Quit the Application.");
while (selection < 1 || selection > 5);
//this does not work!!!!!!
catch( InputMismatchException ime ){
System.out.println("Illegal command.");
}I have
import.java.io.*;at the beginning before i declare my class. I'm not sure abotu the second thing you said, could you elaborate?
I'm sorry, I'm still new at java.
edit: yeah, I didn't import java.util.... hides in shame
Do i still have to import util.Scanner or will that import automatically when i import util.*
Message was edited by:
Cymae -
PLEASE HELP: cannot resolve symbol class
it's showing me the error on the following lines 7 and 9
it says cannot resolve symbol class Name and cannot resolve symbol class Phone
I also have a package name addressBook and it contains two files Entry.java and Address.java
Here is the code:
import java.io.*;
import addressBook.*;
public class AddressDr
public static void main(String[] args)throws IOException
Name name;
Address address;
Phone phone;
Entry entry;
String first, last, middle, street, city, state, zip;
int areaCode, number;
BufferedReader in;
in=new BufferedReader(new InputStreamReader(System.in));
PrintWriter outFile;
outFile=new PrintWriter(new FileWriter("Entries"));
System.out.println("Quit entered fot the first name ends the " + "application.");
System.out.print("Enter first name: ");
first=in.readLine();
while (first.compareTo("Quit") !=0)
System.out.print("Enter last name: ");
last=in.readLine();
System.out.print("Enter middle name: ");
middle=in.readLine();
name=new Name(first, last, middle);
System.out.print("Enter street address: ");
street=in.readLine();
System.out.print("Enter city: ");
city=in.readLine();
System.out.print("Enter state: ");
state=in.readLine();
System.out.print("Enter ZIP code: ");
zip=in.readLine();
address=new Address(street, city, state, zip);
System.out.print("Enter areaCode: ");
areaCode = Integer.parseInt(in.readLine());
System.out.print("Enter number: ");
number=Integer.parseInt(in.readLine());
phone=new Phone(areaCode, number);
entry= new Entry(name, address, phone);
entry.writeToFile(outFile);
System.out.print("Enter first name: ");
first=in.readLine();
outFile.close();
}OK. Here is how I did it.
I have AddressDr which is Address driver.
I have two files Address and Entry which in package addressBook.
AddressDr:
import java.io.*;
import addressBook.*;
public class AddressDr
public static void main(String[] args)throws IOException
Name name;
Address address;
Phone phone;
Entry entry;
String first, last, middle, street, city, state, zip;
int areaCode, number;
BufferedReader in;
in=new BufferedReader(new InputStreamReader(System.in));
PrintWriter outFile;
outFile=new PrintWriter(new FileWriter("Entries"));
System.out.println("Quit entered fot the first name ends the " + "application.");
System.out.print("Enter first name: ");
first=in.readLine();
while (first.compareTo("Quit") !=0)
System.out.print("Enter last name: ");
last=in.readLine();
System.out.print("Enter middle name: ");
middle=in.readLine();
name=new Name(first, last, middle);
System.out.print("Enter street address: ");
street=in.readLine();
System.out.print("Enter city: ");
city=in.readLine();
System.out.print("Enter state: ");
state=in.readLine();
System.out.print("Enter ZIP code: ");
zip=in.readLine();
address=new Address(street, city, state, zip);
System.out.print("Enter areaCode: ");
areaCode = Integer.parseInt(in.readLine());
System.out.print("Enter number: ");
number=Integer.parseInt(in.readLine());
phone=new Phone(areaCode, number);
entry= new Entry(name, address, phone);
entry.writeToFile(outFile);
System.out.print("Enter first name: ");
first=in.readLine();
outFile.close();
Entry:
package addressBook;
import java.io.*;
public class Entry
Name name;
Address address;
Phone phone;
public Entry(Name newName, Address newAddress, Phone phoneNumber)
name = newName;
address = newAddress;
phone = phoneNumber;
public Name knowName()
return name;
public Address knowAddress()
return address;
public Phone knowPhone()
return phone;
public void writeToFile(PrintWriter outFile)
outFile.println(name.knowFirstName());
outFile.println(name.knowLastName());
outFile.println(name.knowMiddleName());
oufFile.println(address.knowStreet());
outFile.println(address.knowState());
outFile.println(address.knowCity());
outFile.println(address.knowZip());
outFile.println(phone.knowAreaCode());
outFile.println(phone.knowDigits());
Address:
package addressBook;
public class Address
String street;
String city;
String state;
String zipCode;
public Address(String newStreet, String newCity, String newState, String zip)
street=newStreet;
city=newCity;
state=newState;
zipCode=zip;
public String knowStreet()
return street;
public String knowCity()
return city;
public String knowState()
return state;
public String knowZip()
return zipCode;
} -
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. -
Cannot resolve symbol: HashMap, put and strings
Hi,
why woudl I get a "cannot resolve symbol" at the line indicated by <============
sec_cands[i] should be a String already.
Can someone help me ?
Thanks in advance.
HashMap temp = new HashMap();
String [] sec_cands = sec_ex.getTargetPhrases();
int sec_length = sec_cands.length;
String [] allCands = new String[total_length];
if (sec_length > 0 ) {
for (int i = 0; i < sec_cands.length; i++)
allCands[fr_length+i] = sec_cands;
temp.put(sec_cands[i], true); <=================Sorry, I accidentally deleted a subscript from a line. The real code is "
HashMap temp = new HashMap();
String [] sec_cands = sec_ex.getTargetPhrases();
int sec_length = sec_cands.length;
String [] allCands = new String[total_length];
if (sec_length > 0 ) {
for (int i = 0; i < sec_cands.length; i++)
allCands[fr_length+i] = sec_cands;
temp.put(sec_cands[i], true); <================= -
Getting error message Cannot Resolve Symbol when trying to compile a class
Hello All -
I am getting an error message cannot resolve symbol while trying to compile a java class that calls another java class in the same package. The called class compiles fine, but the calling class generates
the following error message:
D:\Apache Tomcat 4.0\webapps\examples\WEB-INF\classes\cal>javac
ConnectionPool.java
ConnectionPool.java:158: cannot resolve symbol
symbol : class PooledConnection
location: class cal.ConnectionPool
private void addConnection(PooledConnection value) {
^
ConnectionPool.java:144: cannot resolve symbol
symbol : class PooledConnection
location: class cal.ConnectionPool
PooledConnection pcon = new PooledConnection(con);
^
ConnectionPool.java:144: cannot resolve symbol
symbol : class PooledConnection
location: class cal.ConnectionPool
PooledConnection pcon = new PooledConnection(con);
The code is listed as follows for PooledConnection.java (it compiles fine)
package cal;
import java.sql.*;
public class PooledConnection {
// Real JDBC Connection
private Connection connection = null;
// boolean flag used to determine if connection is in use
private boolean inuse = false;
// Constructor that takes the passed in JDBC Connection
// and stores it in the connection attribute.
public PooledConnection(Connection value) {
if ( value != null ) {
connection = value;
// Returns a reference to the JDBC Connection
public Connection getConnection() {
// get the JDBC Connection
return connection;
// Set the status of the PooledConnection.
public void setInUse(boolean value) {
inuse = value;
// Returns the current status of the PooledConnection.
public boolean inUse() {
return inuse;
// Close the real JDBC Connection
public void close() {
try {
connection.close();
catch (SQLException sqle) {
System.err.println(sqle.getMessage());
Now the code for ConnectionPool.java class that gives the cannot
resolve symbol error
package cal;
import java.sql.*;
import java.util.*;
public class ConnectionPool {
// JDBC Driver Name
private String driver = null;
// URL of database
private String url = null;
// Initial number of connections.
private int size = 0;
// Username
private String username = new String("");
// Password
private String password = new String("");
// Vector of JDBC Connections
private Vector pool = null;
public ConnectionPool() {
// Set the value of the JDBC Driver
public void setDriver(String value) {
if ( value != null ) {
driver = value;
// Get the value of the JDBC Driver
public String getDriver() {
return driver;
// Set the URL Pointing to the Datasource
public void setURL(String value ) {
if ( value != null ) {
url = value;
// Get the URL Pointing to the Datasource
public String getURL() {
return url;
// Set the initial number of connections
public void setSize(int value) {
if ( value > 1 ) {
size = value;
// Get the initial number of connections
public int getSize() {
return size;
// Set the username
public void setUsername(String value) {
if ( value != null ) {
username = value;
// Get the username
public String getUserName() {
return username;
// Set the password
public void setPassword(String value) {
if ( value != null ) {
password = value;
// Get the password
public String getPassword() {
return password;
// Creates and returns a connection
private Connection createConnection() throws Exception {
Connection con = null;
// Create a Connection
con = DriverManager.getConnection(url,
username, password);
return con;
// Initialize the pool
public synchronized void initializePool() throws Exception {
// Check our initial values
if ( driver == null ) {
throw new Exception("No Driver Name Specified!");
if ( url == null ) {
throw new Exception("No URL Specified!");
if ( size < 1 ) {
throw new Exception("Pool size is less than 1!");
// Create the Connections
try {
// Load the Driver class file
Class.forName(driver);
// Create Connections based on the size member
for ( int x = 0; x < size; x++ ) {
Connection con = createConnection();
if ( con != null ) {
// Create a PooledConnection to encapsulate the
// real JDBC Connection
PooledConnection pcon = new PooledConnection(con);
// Add the Connection to the pool.
addConnection(pcon);
catch (Exception e) {
System.err.println(e.getMessage());
throw new Exception(e.getMessage());
// Adds the PooledConnection to the pool
private void addConnection(PooledConnection value) {
// If the pool is null, create a new vector
// with the initial size of "size"
if ( pool == null ) {
pool = new Vector(size);
// Add the PooledConnection Object to the vector
pool.addElement(value);
public synchronized void releaseConnection(Connection con) {
// find the PooledConnection Object
for ( int x = 0; x < pool.size(); x++ ) {
PooledConnection pcon =
(PooledConnection)pool.elementAt(x);
// Check for correct Connection
if ( pcon.getConnection() == con ) {
System.err.println("Releasing Connection " + x);
// Set its inuse attribute to false, which
// releases it for use
pcon.setInUse(false);
break;
// Find an available connection
public synchronized Connection getConnection()
throws Exception {
PooledConnection pcon = null;
// find a connection not in use
for ( int x = 0; x < pool.size(); x++ ) {
pcon = (PooledConnection)pool.elementAt(x);
// Check to see if the Connection is in use
if ( pcon.inUse() == false ) {
// Mark it as in use
pcon.setInUse(true);
// return the JDBC Connection stored in the
// PooledConnection object
return pcon.getConnection();
// Could not find a free connection,
// create and add a new one
try {
// Create a new JDBC Connection
Connection con = createConnection();
// Create a new PooledConnection, passing it the JDBC
// Connection
pcon = new PooledConnection(con);
// Mark the connection as in use
pcon.setInUse(true);
// Add the new PooledConnection object to the pool
pool.addElement(pcon);
catch (Exception e) {
System.err.println(e.getMessage());
throw new Exception(e.getMessage());
// return the new Connection
return pcon.getConnection();
// When shutting down the pool, you need to first empty it.
public synchronized void emptyPool() {
// Iterate over the entire pool closing the
// JDBC Connections.
for ( int x = 0; x < pool.size(); x++ ) {
System.err.println("Closing JDBC Connection " + x);
PooledConnection pcon =
(PooledConnection)pool.elementAt(x);
// If the PooledConnection is not in use, close it
if ( pcon.inUse() == false ) {
pcon.close();
else {
// If it is still in use, sleep for 30 seconds and
// force close.
try {
java.lang.Thread.sleep(30000);
pcon.close();
catch (InterruptedException ie) {
System.err.println(ie.getMessage());
I am using Sun JDK Version 1.3.0_02" and Apache/Tomcat 4.0. Both the calling and the called class are in the same directory.
Any help would be greatly appreciated.
tnx..
addiIs ConnectionPool in this "cal" package as well as PooledConnection? From the directory you are compiling from it appears that it is. If it is, then you are compiling it incorrectly. To compile ConnectionPool (and PooledConnection similarly), you must change the current directory to the one that contains cal and type
javac cal/ConnectionPool. -
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 -
Cannot resolve symbol: class OracleDriver
Attempting to compile a servlet on Apache Server using same jdeveloper jdbc libraries:
classes12.jar & nls_charset12.jar
Error message:
$compilejava2.sh ProdJobs
ProdJobs.java:361: cannot resolve symbol
symbol : class OracleDriver
location: package driver
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Am I missing something else?
JeffreyEnter this code into your program and then put the Oracle jar file that contains the driver in your run-time classpath.
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
catch(ClassNotFoundException cnfe) {
// driver not found
}The effect of this is that the classloader will load the Oracle driver for you then call it's static initiailizer that does a bunch of magic that results in the Java runtime knowing that there's a JDBC driver out there.
It is a little weird - but that's the way it works. -
BufferedReader cannot resolve symbol
Hi,
I need some help with a java program which reads xml files to a specified location, running it on a UNIX machine using Java 1.4.1. I modified the code to include the BufferedReader class, but it keeps complaining about not being able to resolve symbol at line 50 & 53. Any help here would be appreciated, since I'm a newbie.
bash-2.05$ javac outputScript.java
outputScript.java:50: cannot resolve symbol
symbol : constructor InputStreamReader (java.lang.String)
location: class java.io.InputStreamReader
BufferedReader in = new BufferedReader(new InputStreamReader("in"));
^
outputScript.java:53: cannot resolve symbol
symbol : method available ()
location: class java.io.BufferedReader
while (in.available() !=0)
Here's the code:
//package cognos8_3;
import java.io.*;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.File;
* outputScript.java
* Copyright Cognos Incorporated. All Rights Reserved.
* Cognos and the Cognos logo are trademarks of Cognos Incorporated.
* Description: (KB 1013700) - Sample script that will rename output files generated by CM.OUTPUTLOCATION - Cognos 8.3
class outputScript
public static void main(String args[])
String reportName = "";
String reportViewName = "";
String outputLocation = "/data/cognos/rn_filecp/";
String defName = "";
String ofTime = "";
String burstKey = "";
int countRenamed = 0;
// get the list of desc files in the outputlocation
File descFiles = new File(outputLocation);
String[] children = descFiles.list();
if (children == null || children.length == 0)
System.out.println("Invalid file location or no reports found to rename.");
else
System.out.println("Found " + children.length + " files in this location, search for file names containing '_desc.'.");
for (int i=0; i<children.length; i++)
try
// Get filename of file or directory
String filename = children;
if (filename.indexOf("_desc.")>=0)
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(outputLocation+filename);
FileInputStream bis = new FileInputStream(fstream);
BufferedReader in = new BufferedReader(new InputStreamReader("bis.in"));
// Continue to read lines while there are still some left to read
while (in.available() !=0)
String temp = in.readLine();
System.out.println(temp);
// check for report name
if (temp.indexOf("report[@name=")>0)
// get beginning of name
int startIndex = temp.indexOf("report[@name='");
String startString;
int endIndex = 0;
if (startIndex > 0)
startString = temp.substring(startIndex);
startIndex = startString.indexOf("'") + 5; //' 6 characters
endIndex = startString.lastIndexOf("'");
else
startIndex = temp.indexOf("report[@name=");
startString = temp.substring(startIndex);
startIndex = startString.indexOf("@name=") + 6; //' 6 characters
endIndex = startString.lastIndexOf("]");
// get report name
reportName = startString.substring(startIndex+1, endIndex);
//System.out.println("Found report name - " + reportName);
else if (temp.indexOf("reportView[@name=")>0)
// get beginning of name
int startIndex = temp.indexOf("reportView[@name='");
String startString;
int endIndex = 0;
if (startIndex > 0)
startString = temp.substring(startIndex);
startIndex = startString.indexOf("'") + 5; //' 6 characters
endIndex = startString.lastIndexOf("'");
else
startIndex = temp.indexOf("reportView[@name=");
startString = temp.substring(startIndex);
startIndex = startString.indexOf("@name=") + 6; //' 6 characters
endIndex = startString.lastIndexOf("]");
// get report name
reportViewName = startString.substring(startIndex+1, endIndex);
//System.out.println("Found reportView name - " + reportViewName);
else if (temp.indexOf("</fileName>")>0) //check for default name
defName = temp.substring(temp.indexOf(">")+1, temp.lastIndexOf("<"));
else if (temp.indexOf("asOfTime")>=0) // get the time to assure uniqueness when saving
ofTime = temp.substring(temp.indexOf(">")+1, temp.lastIndexOf("<"));
// clean colons from time
ofTime = ofTime.replaceAll(":","_");
else if (temp.indexOf("</burstKey>")>=0)
burstKey = temp.substring(temp.indexOf(">")+1, temp.lastIndexOf("<"));
in.close();
if (reportName.length() == 0)
reportName = reportViewName;
//System.out.println("Renaming using view name - no report name found");
String format = defName.substring(defName.length()-3, defName.length());
// new description xml file
File file = new File(outputLocation+filename);
File newDescFile = new File(outputLocation + reportName+"_"+burstKey+"_"+ofTime+"DESC_" + format+ ".xml");
// new renamed specific format file.
File file3 = new File(outputLocation+defName);
File newDefFile = new File(outputLocation + reportName+"_"+burstKey+"_"+ofTime+"."+format);
boolean success = file3.renameTo(newDefFile);
if (!success)
// File was not successfully renamed
System.out.println("ERROR attempting to rename - " + file3.getAbsolutePath() + " to \n\t\t" +
newDefFile.getAbsolutePath());
else
countRenamed++;
// File was successfully renamed
System.out.println(countRenamed +") Renamed - " + file3.getAbsolutePath() + " to \n\t\t" +
newDefFile.getAbsolutePath());
// Rename file (or directory)
success = file.renameTo(newDescFile);
if (!success)
// File was not successfully renamed
System.out.println("ERROR attempting to rename - " + file.getAbsolutePath() + " to \n\t\t" +
newDescFile.getAbsolutePath());
else
// File was successfully renamed
System.out.println(" - " + file.getAbsolutePath() + " to \n\t\t" +
newDescFile.getAbsolutePath());
catch (Exception e)
System.err.println("File input error " + e.getMessage()) ;
System.out.println("Complete.");
Thanks,
Nick
Edited by: nickmills on Aug 31, 2008 5:05 PMFirst, you only need to create the FileInputStream once. Then that's what you pass to the InputStreamReader constructor. Your code for reading from the BufferedReader is also wrong.FileInputStream fstream = new FileInputStream(outputLocation+filename);
// FileInputStream bis = new FileInputStream(fstream); <-- remove this line
BufferedReader in = new BufferedReader(new InputStreamReader(fstream));
// available() doesn't do what you think it does; forget about it.
// Here's the standard way to use a BufferedReader
String line = null;
while ((line = in.readLine()) != null)
// process 'line'
} There are probably other errors in the code, but reading all that unformatted code is too much of a hassle. In future, please use {code} tags when posting source code. -
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.
Maybe you are looking for
-
Possible Solution - Unable to create a secure connection in Windows 7
Issue: I was unable to create a secure connection to the iTunes store from iTunes, and got a message recommending I check my date and time settings. My date, time, and time zone settings were correct, and iTunes was allowed through Windows firewall.
-
Web pages autodirected to Parking.ps
Hi Everyone, Have been facing a problem since many days now. Everytime I click on a link in any page, it is autodirected to A website called Parking.ps. This happens mostly when, I try to open any videos in youtube or anyother Sites... What is this a
-
Screen Field Value Should be changed based on changes in ALV values
Hi All, We had created a ALV with container, in this Alv we have a checkbox, which is editable. Based on the selection on checkbox , we need to update a field "Total selected" on screen. we are using Event to handle data changed in ALV, but some how
-
Hi, The image slider on the home page of a bc site I administer is not loading properly. If you click on the business logo to refresh then it appears. However the client is not happy that it is not working when a customer lands on the homepage. Has a
-
New iPhone 4 8gb storage questions!!!!
My mom just ordered me a iPhone 4 which is in the 8gb. I love music and im basically worried I won't be able to download all of my music. I understand that I can find ways to take stuff off my iPhone and add more things, but I don't know how. I also