Cannot  resolve symbol - attempt to use System.out.printf

Hi All,
I adapted a HelloWorld program to use
System.out.printf instead of System.out.println (just for a test)
The println comand compiles fine with no errors, but for some reason the printf generates compile time error. Please let me know what am doing wrong.
Below is the error:
d:\j2sdk1.4.1_05\bin>javac HelloWorld.java
HelloWorld.java:6: cannot resolve symbol
symbol : method Printf (java.lang.String,java.lang.String)
location: class java.io.PrintStream
System.out.printf("%s","Hello, world!");
^
1 error
code:
public class HelloWorld {
public static void main (String[] args) {
System.out.printf("%s","Hello, world!");
}

If you check the documentation you can see this method was added in version 1.5
http://java.sun.com/j2se/1.5.0/docs/api/java/io/PrintStream.html#printf(java.util.Locale,%20java.lang.String,%20java.lang.Object...)
BTW: I suggest you use a current version of java, either 1.4.2_09 or 1.5.0_04

Similar Messages

  • "cannot resolve symbol" error when using super.paintComponent

    I am trying to override the paintComponent method in a class extending a JFrame, but when I call super.paintComponent(g) from inside the overridden method I get the error
    QubicGUI.java:63: cannot resolve symbol
    symbol : method paintComponent (java.awt.Graphics)
    location: class javax.swing.JFrame
    super.paintComponent(g);
    ^
    1 error
    I can't see where I am deviating from examples I know work. It is a very small program, so I have included it here:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import java.net.URL;
    class QubicGUI extends JFrame
         private int width;
         private int height;
         private Image background;
         public int getWidth()
         {     return width;     }
         public int getHeight()
         {     return height;     }
         public boolean isOpaque()
    return true;
         public QubicGUI()
              super("Qubic"); //set title
              // The following gets the default screen device for the purpose of finding the
              // current settings of height and width of the screen
         GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
              GraphicsDevice device = environment.getDefaultScreenDevice();
              DisplayMode display = device.getDisplayMode();
              width = display.getWidth();
              height = display.getHeight();
              // Here we set the window to cover the entire screen with a black background, and
              // remove the decorations. (This includes the title bar and close, minimize and
              // maximize buttons and the border)
              setUndecorated(false);
              setVisible(true);
              setSize(width,height);
              setResizable(false);
              setBackground(Color.black);
              // Initializes the background Image
              Image background = Toolkit.getDefaultToolkit().getImage("background.gif");
              // This is included for debugging with a decorated window.
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    } // end constructor
              public void paintComponent(Graphics g)
                   super.paintComponent(g);     
              } // end paintComponenet
    } // end QubicGUI

    Two things I want to know:
    1. I was trying to access a variable as JLabel
    myLabel; defined in the constructor of a class from
    the constructor of another class. I got this error
    message - "Cannot access non-static variable from a
    static context". Why(When both are non-static am I
    getting the message as static context)?Post some code. It's hard to pinpoint a syntax error like that without seeing the code.
    Also, there may be cleaner ways of doing what you want without having classes sharing labels.
    2. I am using a map to set the attributes of a font.
    One of the key-value pair of the map is
    TextAttributesHashMap.put(TextAttribute.FOREGROUND,Colo
    .BLUE);
    But when I using the statement g.drawString("First
    line of the address", 40, 200); the text being
    displayed is in black and not blue. Why?You need to use the drawString that takes an AttributedCharacterIterator:
    import java.awt.*;
    import java.awt.font.*;
    import java.text.*;
    import javax.swing.*;
    public class Example  extends JPanel {
        public static void main(String[] args)  {
            JFrame f = new JFrame("Example");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Container cp = f.getContentPane();
            cp.add(new Example());
            f.setSize(400,300);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            String text = "Every good boy does fine always";
            AttributedString as = new AttributedString(text);
            as.addAttribute(TextAttribute.FAMILY, "Lucida Bright");
            as.addAttribute(TextAttribute.SIZE, new Float(16));
            as.addAttribute(TextAttribute.FOREGROUND, Color.BLUE, 0, 5);
            as.addAttribute(TextAttribute.FOREGROUND, Color.GREEN, 6, 10);
            as.addAttribute(TextAttribute.FOREGROUND, Color.RED, 11, 14);
            as.addAttribute(TextAttribute.FOREGROUND, Color.YELLOW, 15, 19);
            as.addAttribute(TextAttribute.FOREGROUND, Color.MAGENTA, 20, 24);
            as.addAttribute(TextAttribute.FOREGROUND, Color.CYAN, 25, 31);
            g.drawString(as.getIterator(), 10, 20);

  • Can't figure out why an object isn't visible - CANNOT RESOLVE SYMBOL

    I have a simple 3 class app, all in the same package. Classes are:
    - BjackServlet, BjackDAO, and Player
    I get the compile error (I'm using Ant):
    [javac] C:\Tomcat4118\src\webapps\hellobjack\src\mybjpack\BjackServlet.java
    59: cannot resolve symbol
    [javac] symbol : variable thePlayer
    [javac] location: class mybjpack.BjackServlet
    [javac] String gp = thePlayer.getPassword();
    The pertinent code from the 3 classes is below. The offending code is in bold. Why can't I see the object from the BjackServlet.doGet() method? I can see it from within BjackDAO.addPlayer() after the "thePlayer" object has been instantiated. Please help...thanks in advance!
    package mybjpack;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    import java.lang.*;
    public class BjackServlet extends HttpServlet {
         private BjackDAO theBlackjackDAO;
         public void init() throws ServletException {
              String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
              String dbUrl = "jdbc:microsoft:sqlserver://localhost:1433";
              String dbuserid = "testlogin";
              String dbpass = "1climb1";
              String dbname = "ejh_blackjack1";
              String connectstring = "jdbc:microsoft:sqlserver://localhost:1433;User=testlogin;Password=1climb1;DatabaseName=ejh_blackjack1";
         try {
           theBlackjackDAO = new BjackDAO(driver, dbUrl, dbuserid, dbpass, dbname, connectstring);
         catch (IOException exc) {
              System.err.println(exc.toString());
         catch (ClassNotFoundException cnf) {
              System.err.println(cnf.toString());
         catch (SQLException seq) {
              System.err.println(seq.toString());
      public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
        doGet(request, response);
      public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
         String command = request.getParameter("command");
         if (command == null || (command.equals("stats"))) { //player wants to go to stats page
         else if (command.equals("Add")) { //a new player adds himself to the game site
              try {
              theBlackjackDAO.addPlayer(request, response);
              String gp = thePlayer.getPassword();
              System.out.println("the Player.getPassword method yields: " + gp);
              catch (Exception exc) {
                   System.err.println(exc.toString());
         else if (command.equals("enter")) { //an experienced player enters via index.html
         else if (command.equals("play")) {
    etc...
    package mybjpack;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    import java.lang.*;
    public class BjackDAO {
         private Connection myConn;
         public Player thePlayer;
         public BjackDAO(String driver, String dbUrl, String dbuserid, String dbpass, String dbname, String connectstring)
                   throws IOException, ClassNotFoundException, SQLException {
              System.out.println("Loading driver: " + driver);
              Class.forName(driver);
              System.out.println("Connection to: " + dbUrl);
              myConn = DriverManager.getConnection(connectstring);
              System.out.println("Connection successful! Database is " + dbname);
         public void addPlayer(HttpServletRequest request, HttpServletResponse response)
                   throws IOException, SQLException, NumberFormatException {
              //* read all the form values ...
              String ppass = request.getParameter("formpass");
              String puser = request.getParameter("formuser");
              int ppile = Integer.parseInt(request.getParameter("pile"));
              int pstatus = 1;
              int pbet = Integer.parseInt(request.getParameter("bet"));
              int paccount = Integer.parseInt(request.getParameter("account"));
              //* and write them to player object instance variables
              System.out.println("Player instantiation beginning...");
              Player thePlayer = new Player(pstatus, ppile, pbet, puser, paccount, ppass);
              String insertSql =
                   "INSERT INTO tbl_player (user_id, psswrd, account, default_pile, default_bet) "
                   + "VALUES ('" + puser + "', '" + ppass + "', '" + paccount + "', "
                   + "'" + ppile + "', '" + pbet + "')";
                   Statement myStmt = myConn.createStatement();
                   myStmt.execute(insertSql);
                   myStmt.close();
              return;
    package mybjpack;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    import java.lang.*;
    public class Player implements java.io.Serializable {
         private String ouser;
         public String opass;
         private int opile;
         private int oaccount;
         private int obet;
         private int ostatus;
         public Player(int theStatus, int thePile, int theBet,
                             String theUser, int theAccount, String thePass) {
              ouser = theUser;
              opass = thePass;
              opile = thePile;
              oaccount = theAccount;
              obet = theBet;
              ostatus = theStatus;
         public String getUser(){
              return ouser;
         public void setUser(String vuser){
              String ouser = vuser;
         public String getPassword(){
              return opass;
         public void setPassword(String vpass){
              String opass = vpass;
         public int getPile(){
              return opile;
         public void setPile(int vpile){
              int opile = vpile;
         public int getBet(){
              return obet;
         public void setBet(int vbet){
              int obet = vbet;
         public int getAccount(){
              return oaccount;
         public void setAccount(int vaccount){
              int oaccount = vaccount;
         public int getStatus(){
              return ostatus;
         public void setStatus(int vstatus){
              int ostatus = vstatus;

    First glance, try this
    String gp = theBlackjackDAO.thePlayer.getPassword();

  • 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.
    satish

    hi
    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.

  • Having Problem with using JUnit...causes "cannot resolve symbol" problems..

    Hello, say i have a class
    A
    that contains an object of class B.
    Now there's class X...
    It's all fine and dandy trying to compile them both until i try to set the classpath for junit, by doing:
    set classpath=%classpath%;C:\junit3.8.1\junit.jar
    i'm pretty sure it's correct...
    well once i type in this line into my command prompt (win 2k), the junit package now seems to be recognized by class X, which is my testing class that contains an object of class A.
    but NOW class A can't find class B and i get a cannot resolve symbol error. Same goes for class X not being able to find class A.
    Anyone have any suggestions? I'm a newb to this :( . Thanks.

    nevermind! noob mistake.

  • Problem using PixelGrabber ( cannot resolve symbol ) - newbie

    Hi All,
    I have a problem with my short program because the compiler write this (jdk1.4) :
    img.java:17: cannot resolve symbol
    symbol : constructor PixelGrabber (java.awt.Image,int,int,int,int,int[],int)
    location: class java.awt.image.PixelGrabber
    PixelGrabber pg = new PixelGrabber(image,0,0,image.getWidth(this
    ),image.getHeight(this),pixels,0);
    ^
    1 error
    ... And I wrote that in my code :
    ( all is OK, the bug is only when I uncomment the line where the PixelGrabber object
    is needed in my program ).
    Thanks if you have any idea of solution to solve this problem or a doc,
    ( I don't find the answer to my problem in http://java.sun.com/j2se/1.4/docs/api/java/awt/image/PixelGrabber.html ),
    import java.awt.*;
    import java.awt.image.*;
    import java.applet.*;
    import java.awt.image.PixelGrabber;
    public class img extends Applet {
    Image image;
    int pixels[];
    public void init() {
    image = getImage(getDocumentBase(), "rouge.jpg");
    pixels = new int[image.getWidth(this) * image.getHeight(this)];
    PixelGrabber pg = new PixelGrabber(image,0,0,image.getWidth(this),image.getHeight(this),pixels,0);
         pg.grabPixels();
    public void paint(Graphics g) {
              String s = Integer.toString(pixels[5], 16);
              g.drawString(s, 50, 50);

    Hi,
    PixelGrabber needs one more parameter scansize (width).
    change this line;
    PixelGrabber pg = new PixelGrabber(image,0,0,image.getWidth(this),image.getHeight(this),pixels,0);
    to:
    PixelGrabber pg = new PixelGrabber(image,0,0,image.getWidth(this),image.getHeight(this),pixels,0, image.getWidth(this)
    );

  • 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=&apos;");
                                       String startString;
                                       int endIndex = 0;
                                       if (startIndex > 0)
                                            startString = temp.substring(startIndex);
                                            startIndex = startString.indexOf("&apos;") + 5; //&apos; 6 characters
                                            endIndex = startString.lastIndexOf("&apos;");
                                       else
                                            startIndex = temp.indexOf("report[@name=");
                                            startString = temp.substring(startIndex);
                                            startIndex = startString.indexOf("@name=") + 6; //&apos; 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=&apos;");
                                       String startString;
                                       int endIndex = 0;
                                       if (startIndex > 0)
                                            startString = temp.substring(startIndex);
                                            startIndex = startString.indexOf("&apos;") + 5; //&apos; 6 characters
                                            endIndex = startString.lastIndexOf("&apos;");
                                       else
                                            startIndex = temp.indexOf("reportView[@name=");
                                            startString = temp.substring(startIndex);
                                            startIndex = startString.indexOf("@name=") + 6; //&apos; 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 PM

    First, 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 &#x7B;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 me

    The 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

  • "cannot resolve symbol" in a Timer !!!Please Help!!!

    I am doing a program for a class which involves timers. I am using JCreator and when i try to construct a new timer, the compiler points to the "new" in the line:
    Timer T1=new Timer(interval, ActionListener);
    ^
    This is what it looks like and the error reads: cannot resolve symbol; constructor Timer.
    please tell me if yiou have any information or suggestions as to how this error might be remedied.

    Sure, here it is:
    import java.awt.event.*;
    import javax.swing.Timer;
    import javax.swing.JOptionPane;
    import java.util.*;
    interface ActionListener
         void actionPerformed(ActionEvent event);     
    class Ploid
         public static void main(String[] args)
              class Car implements ActionListener
                   int mpg=30;
                   int mph=35;
                   int gtank=20;
                   int interval;
                   int changer;
                   int totalmiles;
                   Car(int x)
                        interval=x;
                   public void actionPerformed(ActionEvent event)
                        for(int c=0;c<(interval/1000);c++)
                             totalmiles=totalmiles+mph;
                        int hyt=mpg*gtank;
                        if(totalmiles>hyt)
                             int y=totalmiles-hyt;
                             totalmiles=totalmiles-y;
                             System.out.println(totalmiles);
                        else
                             System.out.println(totalmiles);
    class SUV implements ActionListener
         int mpg=15;
         int mph=55;
         int gtank=30;
         int interval;
         int changer;
         int totalmiles;
         SUV(int x)
              interval=x;
              public void actionPerformed(ActionEvent event)
                   for(int c=0;c<(interval/1000);c++)
                        totalmiles=totalmiles+mph;
                   int hyt=mpg*gtank;
                   if(totalmiles>hyt)
                        int y=totalmiles-hyt;
                        totalmiles=totalmiles-y;
                        System.out.println(totalmiles);
                   else
                        System.out.println(totalmiles);
    class Semi implements ActionListener
         int mpg=60;
         int mph=80;
         int gtank=50;
         int interval;
         int changer;
         int totalmiles;
         Semi(int x)
              interval=x;
         public void actionPerformed(ActionEvent event)
              for(int c=0;c<(interval/1000);c++)
                   totalmiles=totalmiles+mph;
              int hyt=mpg*gtank;
              if(totalmiles>hyt)
                   int y=totalmiles-hyt;
                   totalmiles=totalmiles-y;
                   System.out.println(totalmiles);
              else
                   System.out.println(totalmiles);
              String flag="y";
              String trav=JOptionPane.showInputDialog("How long do you want to drive?(1000=1 hour)");
              int t1=Integer.parseInt(trav);
              Car listen=new Car(t1);
              SUV listener2=new SUV(t1);
              Semi listener3=new Semi(t1);
              final int t2=t1/1000;
              final int t3=t1/t2;
              ActionListener listener=null;
              Timer T1=new Timer(t3, listener);
              Timer T2=new Timer(t3, listener);
              Timer T3=new Timer(t3, listener);
              while(flag.equals("y"))
                   T1.start();
                   T2.start();
                   T3.start();
                   String g=JOptionPane.showInputDialog("Do you want to drive again?");
                   if((g.equals("y"))||(g.equals("Y")))
                        System.out.println("Let's Drive!");
                   else
                        flag=g;
                   System.exit(0);
    }Here is the errors:
    [errors]
    A:\Ploid2.java:116: cannot resolve symbol
    symbol : constructor Timer (int,ActionListener)
    location: class javax.swing.Timer
              Timer T1=new Timer(t3, listener);
    ^
    A:\Ploid2.java:117: cannot resolve symbol
    symbol : constructor Timer (int,ActionListener)
    location: class javax.swing.Timer
              Timer T2=new Timer(t3, listener);
    ^
    A:\Ploid2.java:118: cannot resolve symbol
    symbol : constructor Timer (int,ActionListener)
    location: class javax.swing.Timer
              Timer T3=new Timer(t3, listener);
    ^
    3 errors
    Process completed.
    [errors]
    ****There is the source code and the errors the compiler returns. That should be more help.****

  • 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?
    Jeffrey

    Enter 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.

  • Cannot resolve symbol class Scanner (Error)

    For whatever reason I get the error message "cannot resolve symbol class Scanner" when trying to run this:
    import java.io.*;
    import java.util.*;
    public class NameReversal
         public static void main(String args[])
              System.out.print("Enter your name: ");
              Scanner Reader = new Scanner(System.in);
              String first = Reader.next();
              String finl = Reader.next();
              int z = first.length();
              int v = finl.length();
              int y = z-1;
              int f = y-1;
              for(int i = y; i>=0; z--)
              System.out.print(first.charAt(1));
              System.out.print(" ");
              for(int p = f; p >= 0; p--)
              System.out.println(finl.charAt(p));
    }

    The Scanner class is in the JDK version 1.5 or later. You must be using an earlier version.

  • Oracle jdbc drivers - cannot resolve symbol

    while i'm not new to java, i am new to jdbc. need to connect a java app to an oracle database (hosted by a 3rd party). i have all the connection info. i've crafted a test program, but cannot get it to compile.
    here's the code:
    import java.sql.*;
    public class SimpleJDBC
         public static void main(String[] args) throws SQLException, ClassNotFoundException
         Class.forName(oracle.jdbc.driver.OracleDriver);
         System.out.println("Driver loaded");
         Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@database.host:1521:class"); //, "username", "password");
         System.out.println("Database connected");
         Statement statement = conn.createStatement();
         ResultSet results = statement.executeQuery("select first_name, last_name from user_tbl where last_name = 'Kendall'");
         while(results.next())
              System.out.println(results.getString(1) + "\t" + results.getString(2));
         conn.close();
    }i've set the classpath to the location of the ojdbc14.jar, and it shows in the classpath when i do a "set" on the cmd line. i've tried it in netbeans, eclipse, and straight cmd line.
    i always come up with the same message (cannot resolve symbol) on the line where i call Class.forName(oracle.jdbc.driver.OracleDriver);.
    i've tried compiling and setting the classpath at the same time. i added the ojdbc14.jar to the compile/build paths in both the ides. i even tried using the old classes12.jar. nothing has worked.
    i can't figure out what else there is. within the ides, the intellisense will actually let me put that line in (piece by piece), but then it shows an error.
    any suggestions?

    Place the string name of the driver in quotes.
    - Saish

  • 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.

  • 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);
    }

  • Factory method generateRandomCircle: "cannot resolve symbol"

    I have written 2 classes: Point and Circle, which uses Point objects in order to create a Circle object. I have created a factory method for Point, which creates random Point objects and a for Circle, which does the same. "newRandomInstance" works fine for Point, but "generateRandomCircle" throws a "cannot resolve symbol" error. "main" is inside Point class. What's the problem?
    Thanks
    ================================================
    import java.io.*;
    import java.lang.*;
    import java.util.*;
    public class Circle implements Cloneable
    public static Circle generateRandomCircle()
    int a= (int) (Math.random()* Short.MAX_VALUE);
    int b= (int) (Math.random()* Short.MAX_VALUE);
    Point p=new Point(a,b);
    int r= (int) (Math.random()* Short.MAX_VALUE);
    Circle c= new Circle(p,r);
    return c;
    ===============================================
    import java.io.*;
    import java.lang.*;
    import java.util.*;
    public class Point implements Cloneable, Comparable
    public static Point newRandomInstance()
    int x = (int) (Math.random() * Short.MAX_VALUE);
    int y = (int) (Math.random() * Short.MAX_VALUE);
    return new Point(x,y);
    public static void main (String[] args)
    Circle cRandom= generateRandomCircle(); //doesn't work
    System.out.println(cRandom.getCenter()+" "+ cRandom.getRadius());
    Point randomP= newRandomInstance(); //works OK
    randomP.printPoint();
    }

    I tried "Circle cRandom=
    Circle.generateRandomCircle(); " instead of "Circle
    cRandom= generateRandomCircle();" and it worked. Why
    did this happen?Because generateRandomCircle() exists in class Circle and not in class Point where your are trying to use it.
    >
    Function "newRandomInstance()" works either as
    "Point.newRandomInstance()" or as
    "newRandomInstance()", however. Why does this
    controversy exist?No controversy! Your main() is contained within class Point and as such knows about everything that is declared in class Point() but nothing about what is in class Circle unless you tell it to look in class Circle.

Maybe you are looking for

  • Open KM Navigation Content in Portal Content area

    Folks, We have a km navigation iview and want to open the contents in the portal content area instead of opening the links in a new window. I don't find any configurable options. What are the development effort options and how big is the effort? Any

  • Using functions from Combo Box 'Others:'

    I am trying to use function DENSE_RANK in OWB 9.0.3.33.0. Unfortunately I can not find properly aropriate object form tool box palette. I tried to use JOIN, FILTER, EXPRESSION. Mostly I get error: PL/SQL: ORA-30483: window functions are not properly

  • What is a "media server"

    We presently have several external HDs (500, 750 g and 1 TB in size). They have never been linked. I understand that a "media server" (arrangement?) would solve our problem of "overcrowding" re: photos, DVDs, music, except I am clueless as to what is

  • Zero Value Invoice in SAP

    Hi, I have a scenario as I need to show days 15 cost zero, on the invoice, to show the customer we are giving service fee of charge. Is there any way in SAP where one can create a zero value invoice? The standard FoC (Free of Charge) business process

  • Procedure for recovering Clusterware/DB from te BCV copy

    I have a customer they wanted to setup a test environment (HPUX ) same as their production 11gRAC.They had taken the clone image from both production node & restored to the test machines. Even the ASM Disk are presented to new Test machines. New test