Please, I need help debugging compiler error
I am new to Java and I do not know why the compiler (Forte for Java) has the following error. Seems like the compiler does not accept NEW for adding new entries to a Vector table.
ERROR:
UAL_LearningPrograms/MyVector.java [12:1] non-static variable this cannot be referenced from a static context
mv.vtable.addNode(new Node(names[n]));
JAVA CODE:
package UAL_LearningPrograms;
import java.util.*;
class MyVector {
private Vtable vtable;
public static void main(String[] args){
MyVector mv = new MyVector();
String names[] = {"one","two","three","four","five"};
for (int n;n<names.length;n++)
mv.vtable.addNode(new Node(names[n]));
public MyVector(){ // Class constructor
System.out.println("MyVector_C");
vtable = new Vtable();
public class Node {
private String name;
public Node(String s){name=s;}
public class Vtable extends Vector {
private Vector v;
public Vtable(){v=new Vector();}
public void addNode(Node n){v.add(n);}
You were trying to reference a non-static variable
from a static context... not allowed.
Simple modification allows that code to work.
If this helps... give me the dollars... thanks!
import java.util.*;
class MyVector
private Vtable vtable;
public static void main(String[] args)
String names[] = {"one","two","three","four","five"};
MyVector mv = new MyVector();
mv.vtable.addNodes(names);
} // main
public MyVector()
System.out.println("MyVector_C");
vtable = new Vtable();
} // MyVector
public class Node
private String name;
public Node(String s)
name = s;
} // Node
} // Node
public class Vtable
extends Vector
private Vector v;
public Vtable()
v=new Vector();
} // Vtabl3
public void addNodes(String n[])
for (int i = 0; i < n.length; ++i)
v.add(new Node(n));
} // addNode
public void addNode(Node n)
v.add(n);
} // addNode
} // Vtable
} // MyVector
Similar Messages
-
Need help determining compiling error
Good morning,
I need help finding the cause of a compiling error I receive. I have reviewed my code numerous times without any luck. I hope you guys might see something I am not! The entire file exceeds the limit I can post, so I am attaching it in 2 posts. Sorry for the inconvenience. The error and my code are posted below. Thank you for your help!
C:\StockTrackerDB.java:382: cannot find symbol
symbol : method add(java.lang.Boolean)
location: class java.util.ArrayList<java.lang.String>
aList.add(new Boolean(rs.getBoolean("admin")));
^
1 error
Tool completed with exit code 1
import java.io.*;
import java.sql.*;
import java.util.*;
public class StockTrackerDB
private Connection con = null;
//Constructor; makes database connection
public StockTrackerDB() throws ClassNotFoundException,SQLException
if(con == null)
String url = "jdbc:odbc:StockTracker";
try
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
catch(ClassNotFoundException ex)
throw new ClassNotFoundException(ex.getMessage() +
"\nCannot locate sun.jdbc.odbc.JdbcOdbcDriver");
try
con = DriverManager.getConnection(url);
catch(SQLException ex)
throw new SQLException(ex.getMessage()+
"\nCannot open database connection for "+url);
// Close makes database connection; null reference to connection
public void close() throws SQLException,IOException,ClassNotFoundException
con.close();
con = null;
// Method to serialize object to byte array
private byte[] serializeObj(Object obj) throws IOException
ByteArrayOutputStream baOStream = new ByteArrayOutputStream();
ObjectOutputStream objOStream = new ObjectOutputStream(baOStream);
objOStream.writeObject(obj); // object must be Serializable
objOStream.flush();
objOStream.close();
return baOStream.toByteArray(); // returns stream as byte array
// Method to deserialize bytes from a byte array into an object
private Object deserializeObj(byte[] buf) throws IOException, ClassNotFoundException
Object obj = null;
if(buf != null)
ObjectInputStream objIStream = new ObjectInputStream(new ByteArrayInputStream(buf));
obj = objIStream.readObject(); //IOException, ClassNotFoundException
return obj;
// Methods for adding a record to a table
// add to the Stocks Table
public void addStock(String stockSymbol, String stockDesc) throws SQLException, IOException, ClassNotFoundException
Statement stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO Stocks VALUES ('"
+stockSymbol+"'"
+",'"+stockDesc+"')");
stmt.close();
// add to the Users table
public boolean addUser(User user) throws SQLException,IOException,ClassNotFoundException
boolean result = false;
String dbUserID;
String dbLastName;
String dbFirstName;
Password dbPswd;
boolean isAdmin;
dbUserID = user.getUserID();
if(getUser(dbUserID) == null)
dbLastName = user.getLastName();
dbFirstName = user.getFirstName();
Password pswd = user.getPassword();
isAdmin = user.isAdmin();
PreparedStatement pStmt = con.prepareStatement("INSERT INTO Users VALUES (?,?,?,?,?)");
pStmt.setString(1, dbUserID);
pStmt.setString(2, dbLastName);
pStmt.setString(3, dbFirstName);
pStmt.setBytes(4, serializeObj(pswd));
pStmt.setBoolean(5, isAdmin);
pStmt.executeUpdate();
pStmt.close();
result = true;
else
throw new IOException("User exists - cannot add.");
return result;
// add to the UserStocks table
public void addUserStocks(String userID, String stockSymbol)
throws SQLException,IOException,ClassNotFoundException
Statement stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO UserStocks VALUES ('"
+userID+"'"
+",'"+stockSymbol+"')");
stmt.close();
// Methods for updating a record in a table
// updating the Users table
public boolean updUser(User user) throws SQLException, IOException, ClassNotFoundException
boolean result = false;
String dbUserID;
String dbLastName;
String dbFirstName;
Password dbPswd;
boolean isAdmin;
dbUserID = user.getUserID();
if(getUser(dbUserID) != null)
dbLastName = user.getLastName();
dbFirstName = user.getFirstName();
Password pswd = user.getPassword();
isAdmin = user.isAdmin();
PreparedStatement pStmt = con.prepareStatement("UPDATE Users SET lastName = ?," + " firstName = ?, pswd = ?, admin = ? WHERE userID = ?");
pStmt.setString(1, dbLastName);
pStmt.setString(2, dbFirstName);
pStmt.setBytes(3, serializeObj(pswd));
pStmt.setBoolean(4, isAdmin);
pStmt.setString(5, dbUserID);
pStmt.executeUpdate();
pStmt.close();
result = true;
else
throw new IOException("User does not exist - cannot update.");
return result;
}// Methods for deleting a record from a table
// delete a record from the Stocks table
private void delStock(String stockSymbol) throws SQLException,IOException,ClassNotFoundException
Statement stmt = con.createStatement();
stmt.executeUpdate("DELETE FROM Stocks WHERE "
+"symbol = '"+stockSymbol+"'");
stmt.close();
// delete a record from the Users table
public void delUser(User user) throws SQLException,IOException,ClassNotFoundException
String dbUserID;
String stockSymbol;
Statement stmt = con.createStatement();
try
con.setAutoCommit(false);
dbUserID = user.getUserID();
if(getUser(dbUserID) != null) // verify user exists in database
ResultSet rs1 = stmt.executeQuery("SELECT userID, symbol "
+"FROM UserStocks WHERE userID = '"+dbUserID+"'");
while(rs1.next())
try
stockSymbol = rs1.getString("symbol");
delUserStocks(dbUserID, stockSymbol);
catch(SQLException ex)
throw new SQLException("Deletion of user stock holding failed: " +ex.getMessage());
} // end of loop thru UserStocks
try
{ // holdings deleted, now delete user
stmt.executeUpdate("DELETE FROM Users WHERE "
+"userID = '"+dbUserID+"'");
catch(SQLException ex)
throw new SQLException("User deletion failed: "+ex.getMessage());
else
throw new IOException("User not found in database - cannot delete.");
try
con.commit();
catch(SQLException ex)
throw new SQLException("Transaction commit failed: "+ex.getMessage());
catch (SQLException ex)
try
con.rollback();
catch (SQLException sqx)
throw new SQLException("Transaction failed then rollback failed: " +sqx.getMessage());
// Transaction failed, was rolled back
throw new SQLException("Transaction failed; was rolled back: " +ex.getMessage());
stmt.close();
// delete a record from the UserStocks table
public void delUserStocks(String userID, String stockSymbol) throws SQLException,IOException,ClassNotFoundException
Statement stmt = con.createStatement();
ResultSet rs;
stmt.executeUpdate("DELETE FROM UserStocks WHERE "
+"userID = '"+userID+"'"
+"AND symbol = '"+stockSymbol+"'");
rs = stmt.executeQuery("SELECT symbol FROM UserStocks "
+"WHERE symbol = '"+stockSymbol+"'");
if(!rs.next()) // no users have this stock
delStock(stockSymbol);
stmt.close();
// Methods for listing record data from a table
// Ordered by:
// methods that obtain individual field(s),
// methods that obtain a complete record, and
// methods that obtain multiple records
// Methods to access one or more individual fields
// get a stock description from the Stocks table
public String getStockDesc(String stockSymbol) throws SQLException, IOException, ClassNotFoundException
Statement stmt = con.createStatement();
String stockDesc = null;
ResultSet rs = stmt.executeQuery("SELECT symbol, name FROM Stocks "
+"WHERE symbol = '"+stockSymbol+"'");
if(rs.next())
stockDesc = rs.getString("name");
rs.close();
stmt.close();
return stockDesc;
// Methods to access a complete record
// get User data from the Users table
public User getUser(String userID) throws SQLException,IOException,ClassNotFoundException
Statement stmt = con.createStatement();
String dbUserID;
String dbLastName;
String dbFirstName;
Password dbPswd;
boolean isAdmin;
byte[] buf = null;
User user = null;
ResultSet rs = stmt.executeQuery("SELECT * FROM Users WHERE userID = '" +userID+"'");
if(rs.next())
dbUserID = rs.getString("userID");
dbLastName = rs.getString("lastName");
dbFirstName = rs.getString("firstName");
// Do NOT use with JDK 1.2.2 using JDBC-ODBC bridge as
// SQL NULL data value is not handled correctly.
buf = rs.getBytes("pswd");
dbPswd=(Password)deserializeObj(buf);
isAdmin = rs.getBoolean("admin");
user = new User(dbUserID,dbFirstName,dbLastName,dbPswd,isAdmin);
rs.close();
stmt.close();
return user; // User object created for userID
// Methods to access a list of records
// get a list of selected fields for all records from the Users Table
public ArrayList listUsers() throws SQLException,IOException,ClassNotFoundException
ArrayList<String> aList = new ArrayList<String>();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT userID, firstName, lastName, admin "
+"FROM Users ORDER BY userID");
while(rs.next())
aList.add(rs.getString("userID"));
aList.add(rs.getString("firstName"));
aList.add(rs.getString("lastName"));
aList.add(new Boolean(rs.getBoolean("admin")));
rs.close();
stmt.close();
return aList;
// get all fields in all records for a given user from the UserStocks table
public ArrayList listUserStocks(String userID) throws SQLException, IOException, ClassNotFoundException
ArrayList<String> aList = new ArrayList<String>();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM UserStocks "
+"WHERE userID = '"+userID+"' ORDER BY symbol");
while(rs.next())
aList.add(rs.getString("symbol"));
rs.close();
stmt.close();
return aList;
} -
Newbie needs help on compiling error
I'm reading java 2 programming for dummies, but can't get this example working. I get an error on line 4, but when I remove 'public' from in front of 'class', Iexplore tells me I need a public constructor. I also get errors on line 94 and 98 where the compilator says that the java.awt.Component has been deprecated. I have no clue what that means..
Please help me! I'm stuck...
Here is my code:
/*line 0*/
import java.applet.Applet;
import java.awt.*;
public class PixApplet extends Applet{
public void init() {
Rectgl r = new Rectgl(10,5,Color.red);
Square s = new Square(10,Color.blue);
Circle c = new Circle(20,Color.yellow);
Square s2 = new Square(40,Color.green);
add(r);
add(s);
add(c);
add(s2);
add(new PixLabel(r));
add(new PixLabel(s));
add(new PixLabel(c));
add(new PixLabel(s2));
/*Rectgl*/
class Rectgl extends Pix {
/*Constructor*/
public Rectgl(int width, int height, Color c) {
myDimension.width = width;
myDimension.height = height;
setColor(c);
/*Draw shape*/
public void Paint(Graphics g) {
g.fillRect(0,0,myDimension.width,myDimension.height);
/*Return area*/
public double getArea() {
return (myDimension.width * myDimension.height);
/*Return perimeter */
public double getPerimeter() {
return (myDimension.width + myDimension.height) * 2;
/*Return kind of shape*/
public String getKind() {
return "Rectangle";
/*Square*/
class Square extends Rectgl {
/*Constructor*/
public Square(int side,Color c) {
super(side,side,c);
/*Return kind of shape*/
public String getKind() {
return "Square";
abstract class Pix extends Canvas {
Dimension myDimension = new Dimension();
/*Constructor*/
public void Pix() {
/*Set object's forground color*/
public void setColor(Color c) {
setForeground(c);
public void paint(Graphics g) {
public double getArea() {
return 0;
public double getPerimeter() {
return 0;
public String getKind() {
return "unknown shape";
/*line 93*/
public Dimension preferredSize() {
return myDimension;
/*line 97*/
public Dimension minimumSize() {
return myDimension;
class Circle extends Pix {
private int myRadius;
/*Constructor*/
public Circle(int radius, Color c) {
myRadius = radius;
setColor(c);
myDimension.height = myDimension.width = 2 * radius;
/*Draw shape*/
public void paint(Graphics g) {
g.fillArc(0,0,(2 * myRadius),(2 * myRadius),0,360);
/*Return area*/
public double getArea() {
return (Math.PI * (myRadius * myRadius));
/*Return perimeter*/
public double getPerimeter() {
return 2 * Math.PI * myRadius;
/*Return kind of shape*/
public String getKind() {
return "Circle";
class PixLabel extends TextArea {
/*Constructor*/
public PixLabel(Pix s) {
super( "I am a " + s.getKind() + "\nMy perimeter is " + Double.toString(s.getPerimeter()) + "\nMy area is " + Double.toString(s.getArea()),3,15,SCROLLBARS_NONE);
}OK. You do not need to worry too much about the deprecated messages. They are only warnings and will not stop the program compiling.
What is the name of the java file that your code is in. It should be PixApplet.java
How are you compiling it, something like
javac *.java or javac PixApplet.java
What is the error you get when you try to compile -
Need help with compile error: externally visible definition
I am getting the following error on compile:
"A file found in an source-path must have an externally
visible definition. If a definition in the file is meant to be
externally visible, please put the definition in a package."
Typically this would mean that an actionscript class file is
not placed in a package, but I am getting the error for a Custom
MXML ListItemRenderer component I created.
Does anyone have a clue why this would be happening? It
happened once before and mysteriously went away after I removed all
of the code in the file, saved it, pasted it back in and saved it
again. Unfortunately that is not working this time.
I would really appreciate any help.
Thanks,
shaunOK here it is, first i'll give u the Card.java file, it compiles i think:
public interface Card {
/** The four suites. */
public static final byte CLUB = 0, DIAMOND = 1, HEART = 2, SPADE = 2;
/** The suite of this card. */
public byte suite();
* Is 's' a valid suite?
* @param s a value to check to see if it is a valid suite.
* @return true iff 's' is a valid suite.
public boolean validSuite(byte s);
/** The thirteen standard cards. */
public static final byte ACE = -1, TWO = -2, THREE = -3, FOUR = -4,
FIVE = -5, SOX = -6, SEVEN = -7, EIGHT = -8, NINE = -9, TEN = -10,
JACK = -11, QUEEN = -12, KING = -13;
/** The face-value of this card */
public byte value();
* Is 'v' a valid face-value?
* @param v the value to check to see if it is a valid face-value.
* @return true iff 'v' is a valid face-value.
public boolean validValue(byte v);
* @param a_card the card to compare
* @return true iff the suite of this card is identical to the suite
* of <code>a_card</code>
public boolean sameSuiteAs(Card a_card);
* @param a_card the card to compare
* @return true iff the face value of this card is identical to the
* face value of <code>a_card</code>
public boolean sameFaceValueAs(Card a_card);
* @param a_card the card to compare
* @return true iff the face value of this card is strictly greater than
* the face value of <code>a_card</code>
public boolean greaterFaceValueThan(Card a_card);
* Whether this card has a greater value than <code>a_card</code> is
* determined by a given card game's rules.
* @param a_card the card to compare
* @return true iff this card has a great value than <code>a_card</code>
public boolean greaterValueThan(Card a_card);
* Two cards are equivalent if they are indistinguishable in a given
* card game's rules.
* @param a_card the card to compare
* @return true iff this card and <code>a_card</code> are indistinguishable
public boolean equivalentTo(Card a_card);
} -
please help..i tried everything but it doesn`t work..
"everything" is a big list, probably hundreds of possibilities. If you list specifically what you have tried someone may be able to help you. This article may help also: http://support.apple.com/kb/TS3694#error1602
-
Please, I need help installing Ps2: error message: 106
On a friend's PC, during installation of Elements 2, the installation program aborts at about 39% complete with the following error message:
Component MoverData had the following error:
Media Name: Data
Component: TypeSpt\Fonts
File Group: Required Fonts
File: HYSMyeongJoStd-Medium-Acro.otf
Error No: 106 Refer to on-line Help
I am not sure what exactly on-line help is, but the code does not show up by searching the Help file on my system.
Does anyone know what error 106 is and how I can get past that point? Ih tried it several times with the stopping point always the same.
Thanks,
Jonatas Batista
My Email is: [email protected]Adobe has this for the error:
http://kb2.adobe.com/cps/171/tn_17120.html
If you google the 106 error, you also come up with results that indicate a dirty or damaged disc.
You might be able to install it by copying the contents of the disc into a folder on your desktop. Install from this desktop folder. This works with the insert disc 1 error. I'm not sure if it will work for the 106 error but it would be worth a try. -
'class' or 'interface' expected
public static int getNewAmount()
^
Can anyone tell me what to do?
Thx.I solved that problem. Thanks.
But now I have another error problem.
Exception in thread "main" java.lang.NumberFormatException: n
at java.lang.Integer.parseInt(Integer.java:414)
at java.lang.Integer.parseInt(Integer.java:463)
at MyInput.readInt(MyInput.java:27)
at SalaryComputation3.getJobClass(SalaryComputation3.java:85)
at SalaryComputation3.main(SalaryComputation3.java:61) -
Please help with compiling error
Hello, I am currently taking a class in Java Programming and need help with an error. I am working on a Mortgage Calculator and when I compile the code I get this error. I have no idea how to fix this. Can anyone help? Thank you.
'{' expected public class MortgageCalculator
1 error
Tool completed with exit code 1
Here is my code
import java.io.*;//*java input output
import java.util.Date;//Date Utility
import java.util.Formatter;//format Utility
import java.text.NumberFormat;//*format numbers
//class MortgageCalculator
public class MortgageCalculator
public static void main(String[]args);{
Date currentDate=newDate();
DecimalFormat decimalPlaces=newDecimalFormat("0.00");
//declare Variables
final double principalBalance=200000;//*$200,000 Loan
final double monthlyInterest=.06;//*6% interest rate
final double Term=12*30;//*monthly interest rate
final double monthlyInterest=((principalBalance*(monthlyInterest/12))/(1-Math.pow(1+(monthlyInterest/12))-(Term)));
//Display Output
System.out.println("\t\t" + currentDate);
System.out.println("\t\tLoan Amount" + principalBalance);
System.out.println("\t\tInterest Rate" + monthlyInterest);
System.out.println("\t\tTerm of Loan" + Term);
System.out.println("\t\tThe Payment will be:" + monthlyInterest);
System.out.println(decimalPlaces.format(mothlyInterest));
}You need to enclose your class body in { }. You're missing at least one of them
-
Hello, I have a problem on my iPhone every second turn on and off I mean it shows the apple and off and again shows the apple icon and off and tried to Restore and it hangs on my iPhone and then waits Error 3004 Please I need help please!
Resolve communication issues
Related errors: 17, 1004, 1013, 1638, 3014, 3194, 3000, 3002, 3004, 3013, 3014, 3015, 3194, or 3200.
These alerts refer to gs.apple.com, say "There was a problem downloading the software," or say the "device isn't eligible for the requested build."
I would guess your iphone has been hacked ( jailbroken ) ring any bells ? -
Installing Elements 11 on Mac 10.8.2. Need help with install error: Setup wants to make changes. Type your password to allow this." After entering Adobe password, nothing happens. Locked from further installation. Any ideas? Adobe phone support could not help.
Just before letting changes (installation in this case) be made on the system, Mac OS prompts for password & this has to be the Mac system password. This password prompt is the system's own native prompt & would accept the system password only. Please make sure it is the right system password (all/admin rights) and the installaion should run.
-
Please, I need help- video messages
Please, I need help. I can not play video messages which send me friends. When I click the message error occur ,and tell me: "Oops, something went wrong. Please try again, or get in touch if you need help." I do not know what I should do. I tried many times to play video message. I updated skype, but nothing has changed. Does anyone know how to help me?
PS. I am sorry for my bad English. I am still learning English.See your other post asking the same question:
help.... ¡¡¡¡ -
If i reset my ipad can i install paye games for free if i sign back into my apple ID. Please i need help because i need to update my games but i need to put in this billing thing and i want to get rid of it so then i cant buy games with my credit card
Hello,
As frustrating as it seems, your best to post any frustrations about the iPhone in the iPhone discussion here:
https://discussions.apple.com/community/iphone/using_iphone
As this discussion is for iBook laptops.
Best of Luck. -
When i type in my correct password on the login screen and press enter it just goes to a blue screen for a few seconds then goes back to the same login screen again, please i need help?
You can take some of the steps here, #4, #5 or even trying a #18
Step by Step to fix your Mac
but I suspect your going to first have to create a data recovery drive
Create a data recovery, undelete boot drive
to get your data off the machine,
then do a #20 to eliminate the bad sectors as that's why your getting the "pinwheel" it's getting a delay reading from the drive, right when your trying to log in too, what a bad spot for it to happen.
Step by Step to fix your Mac -
How can I delete my old iCloud account cause I forgot my password and my email has been block. Please I need help urgently
Contact the Apple account security team for assistance resetting your password: Apple ID: Contacting Apple for help with Apple ID account security.
-
My daughter has spitefully changed my password and has refused to tell me. I have so much medical information that I can not lose. Is there anyway to get around this problem. Please I need Help fast.
Connect the iPod to your syncing computer and restore it via iTunes. However, if iTunes asks for the unknown passcode you need to place the iPod in recovery mode and then restore the iPod from backup. For recovey mode see:
iPhone and iPod touch: Unable to update or restore
"If you cannot remember the passcode, you will need to restore your device using the computer with which you last synced it. This allows you to reset your passcode and resync the data from the device (or restore from a backup). If you restore on a different computer that was never synced with the device, you will be able to unlock the device for use and remove the passcode, but your data will not be present. Refer to Updating and restoring iPhone and iPod touch software."
Above is from:
http://support.apple.com/kb/ht1212
Maybe you are looking for
-
Hi When I edit an event in iCal i can only see the year and time in the from and to fields or if I try and set a repeating event to a date. Is there a way to get them to show again. John
-
TestStand Datalog Use Step Format Setting Resets
I have something unusual happening on two different testers using PXI controllers. In TestStand 3.5, I use the Configure -> Datalog... to set the Numeric Precision to "Use Step Format". I check the box and hit the OK button. If I immediately go in
-
ICloud Photo Library - Updating forever
I've been using iCloud Photo Library since iOS 8.1 without too much problems (apart the fact that syncing between devices is very slow). For no apparent reason, on my iPhone 5 (iOS 8.1.2), icloud photo library is stuck at updating 22 pictures to the
-
i have problem with my iphone 5 when i received calls my phone is freezing and sometimes it appears that is closed. i have issue about some application that freez my phone, please i want a solution
-
So, new to CS 5.5 but I'm in Photoshop right now and I opened up a PDF in Photoshop and I'm deleting the background. So I grab the Polygonal Lasso tool and select my area to delete. Then I hit the Delete key on the keyboard and it pops up the Fill wi