Non-static method destroyApp(boolean) cannot be referenced from a static co

Hi guys, ive been writing, erasing and rewriting code, and finally my midlet runs well. It get complicated when i began to use the class Canvas, because the main process required values from the Canvas class. Im not sure if the program is well designed. Sugestions are apreciated.
Well, i used static public boolean hilo; to share that variable between classes, and its working, however there is just a final procedure I want to implement, and that is that terminate the midlet when the user press the erase button.
When I detect the button, i cant call the notifyDestroyed() method.
Here's the code
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class TS_Online extends MIDlet implements CommandListener {
public static Display display;                    // Objeto para que muestre en pantalla
private SSCanvas sscInicio;               // Objeto canvas para mostrar imagenes
private Form frmServidor;                    // Objeto forma
private TextField ip1;                         // Direcci�n IP
private TextField ip2;                         // Direcci�n IP
private TextField ip3;                         // Direcci�n IP
private TextField ip4;                         // Direcci�n IP
private TextField puerto;                    // Puerto a conectarse
private Command cmdEntrada;               // Objeto comando
private Command cmdSalida;                    // Objeto comando
private Command cmdVolver;                    // Objeto comando
// * Constructor *
public TS_Online() {
     display = Display.getDisplay(this);                    // Obtiene la pantalla
     sscInicio = new SSCanvas();                              // Nueva forma
     cmdEntrada = new Command("Entrada", Command.STOP, 2);
     cmdSalida = new Command("Salida", Command.STOP, 2);
     cmdVolver = new Command("Volver", Command.BACK, 1);
     sscInicio.addCommand(cmdEntrada);                    // Coloca el comando Entrada
     sscInicio.addCommand(cmdSalida);                    // Coloca el comando Salida
     sscInicio.setCommandListener(this);                    // Define la forma que escucha comandos
     ip1 = new TextField("Direcci�n IP:", "0", 3, TextField.NUMERIC);     // Caja de texto
     ip2 = new TextField(null, "0", 3, TextField.NUMERIC);
     ip3 = new TextField(null, "0", 3, TextField.NUMERIC);
     ip4 = new TextField(null, "0", 3, TextField.NUMERIC);
     puerto = new TextField("Puerto:", "24300", 5, TextField.NUMERIC);
     frmServidor = new Form("Configuraci�n");          // Titulo de la forma
     frmServidor.append(ip1);
     frmServidor.append(ip2);
     frmServidor.append(ip3);
     frmServidor.append(ip4);
     frmServidor.append(puerto);
     frmServidor.addCommand(cmdVolver);                    // Coloca el comando Salida
// * Metodos *
public void startApp() {
     sscInicio.hilo = true;                                   // Habilita el hilo
     new Thread(sscInicio).start();                         // Hilo en Canvas
     display.setCurrent(sscInicio);                         // Define objeto a mostrar
     sscInicio.setTitle("TicketShop S.A.");               // Titulo de la forma
// Metodos comunes en todos los Midlet
public void pauseApp() {
     System.out.println("*** Pausado ***");
     sscInicio.hilo = false;                                   // Detiene el hilo
public void destroyApp(boolean unconditional) {
     sscInicio.hilo = false;
     System.out.println("*** Terminado ***");
     notifyDestroyed();
public void commandAction(Command c, Displayable s) {
     if (c == cmdEntrada) {
          if (sscInicio.img == sscInicio.ts) {          // Configurar servidor
               sscInicio.hilo = false;
               sscInicio.ip = true;
               System.out.println(sscInicio.hilo);
               frmServidor.setCommandListener(this);
               display.setCurrent(frmServidor);
          } else {
               sscInicio.valido();                              // Tiquete valido
     } else if (c == cmdSalida) {
          sscInicio.invalido();                              // Tiquete invalido
     } else if (c == cmdVolver) {                         // Volver a la pantalla anterior
          sscInicio.setCommandListener(this);
          sscInicio.hilo = true;                              // Arranca el hilo
          new Thread(sscInicio).start();                    // Hilo en Canvas
          display.setCurrent(sscInicio);
          System.out.println(sscInicio.hilo);
// * Clase graficadora *
class SSCanvas extends Canvas implements Runnable {
private int sleepTime;                                        // Tiempo de retrazo
static public boolean ip;                                   // Configurar IP
static public boolean hilo;                              // Continuar hilo
static public Image ts = null;                         // Contenedor imagen
static public Image rojo = null;                         // Contenedor imagenpri
static public Image verde = null;                         // Contenedor imagen
static public Image img = null;                         // Contenedor imagen
static public String mensaje = null;                    // Cadena de salida
//private CommConnection cc = null;                         // Conector para puerto
private SocketConnection sc = null;                    // Conector para red
private SocketConnection cc = null;                    // Conector para red
public SSCanvas() {
     // Cargamos las im�genes a usar
     try {
          ts = Image.createImage("/TicketShop.PNG");     // Procedimiento para cargar las imagenes
          rojo = Image.createImage("/Rojo.PNG");          // Procedimiento para cargar las imagenes
          verde = Image.createImage("/Verde.PNG");     // Procedimiento para cargar las imagenes
     } catch (IOException e) {}                              // Error si no encuentra las imagenes
void iniciar() {
     img = ts;                                                  // Imagen de bienvenida
     mensaje = "Conectando al servidor";                    // Mensaje de inicio
     // Tiempo de espera para configurar servidor
     for (sleepTime = 1;sleepTime <= 3; sleepTime++) {
          try {
               mensaje = mensaje + ".";                    // Mensaje de inicio
               repaint();                                        // Redibuja la pantalla
               serviceRepaints();                              // Espera que termine
               Thread.sleep(1000);
          } catch (InterruptedException e) {
               System.out.println(e.toString());
     sleepTime = 50;
     img = verde;
     System.out.println("Iniciar");
void codigo() {
void valido() {
     img = verde;                                             // Imagen OK
     mensaje = "Tiquete OK";                                   // Tiquete valido
     AlertType.CONFIRMATION.playSound(TS_Online.display);     // Sonido
void invalido() {
     img = rojo;                                                  // Imagen OK
     mensaje = "Tiquete Inv�lido";                         // Tiquete valido
     AlertType.ERROR.playSound(TS_Online.display);     // Sonido
// thread que contiene el game loop
public void run() {
     System.out.println("*** Hilo arrancado ***");
     if (img == null)
          iniciar();
     while (hilo) {
          System.out.println("Hilo");
          // Actualizar pantalla
          repaint();                                                  // Redibuja la pantalla
          serviceRepaints();                                        // Espera que termine
          try {
               Thread.sleep(sleepTime);
          } catch (InterruptedException e) {
               System.out.println(e.toString());
public void keyPressed(int keyCode) {
     if (keyCode == -8) {                                        // Si presiona borrar
          hilo = false;                                   // Salir de la aplicacion
          System.out.println("*** Terminado ***");
          TS_Online.destroyApp(true);
          notifyDestroyed();
public void paint(Graphics g) {
     // Borrar la pantalla
     g.setColor(255,255,255);
     g.fillRect (0, 0, getWidth(), getHeight());
     // Coloca la imagen correspondiente
     g.drawImage (img, getWidth()/2, 10, Graphics.HCENTER|Graphics.TOP);
     // Poner texto
     Font fuente = Font.getFont (Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_MEDIUM);
     g.setFont(fuente);
     g.setColor(0,0,0);
     g.drawString(mensaje, getWidth()/2, getHeight() - 40,Graphics.TOP|Graphics.HCENTER);
}Im using the boolean hilo to stop the thread. I seems to work fine for me. By the way, im using 4 textFields to get the IP address, however they appear one over the other, id like to see them one next to the other, or a better way to validate an IP address.
Thanks for the help!!

Well, the solution was really easy, i just needed to create a reference to the midlet inside the Canvas class public SSCanvas(MIDlet m), so i got this new code, however, it seems cool in the emulator but i still cant get two comands in a row in the phone.
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.rms.*;
public class TS_Online extends MIDlet implements CommandListener {
public static Display display;               // Objeto para que muestre en pantalla
private SSCanvas sscInicio = null;          // Objeto canvas para mostrar imagenes
private Form frmServidor;                    // Objeto forma
private StringItem subtitulo;               // Subtitulo de la forma
private TextField[] ip;                    // Direcci�n IP
private TextField puerto;                    // Puerto a conectarse
private Command cmdEntrada;               // Objeto comando
private Command cmdSalida;                    // Objeto comando
private Command cmdVolver;                    // Objeto comando
private String direccion;                    // Direcci�n del socket
private RecordStore rsDireccion = null;     // Almacenamiento RMS
// * Constructor *
public TS_Online() {
     display = Display.getDisplay(this);                    // Obtiene la pantalla
     sscInicio = new SSCanvas(this);                    // Nueva forma con ref este midlet
     cmdEntrada = new Command("Entrada", Command.STOP, 2);
     cmdSalida = new Command("Salida", Command.STOP, 2);
     cmdVolver = new Command("Volver", Command.BACK, 1);
     sscInicio.addCommand(cmdEntrada);                    // Coloca el comando Entrada
     sscInicio.addCommand(cmdSalida);                    // Coloca el comando Salida
     sscInicio.setTitle("TicketShop S.A.");               // Titulo del canvas
     // Constructor forma Configurar Servidor
     ip = new TextField[4];                                   //
     ip[0] = new TextField(null, "190", 3, TextField.NUMERIC);     // Caja de texto
     ip[1] = new TextField(null, "65", 3, TextField.NUMERIC);
     ip[2] = new TextField(null, "161", 3, TextField.NUMERIC);
     ip[3] = new TextField(null, "158", 3, TextField.NUMERIC);
     puerto = new TextField("Puerto:", "24300", 5, TextField.NUMERIC);
     ip[0].setLayout(Item.LAYOUT_2);                         // Coloca los elementos pegados
     ip[1].setLayout(Item.LAYOUT_2);
     ip[2].setLayout(Item.LAYOUT_2);
     ip[3].setLayout(Item.LAYOUT_2);
     frmServidor = new Form("Configuraci�n");          // Titulo de la forma
     subtitulo = new StringItem("Direccion IP:", "");
     frmServidor.append(subtitulo);                         // Coloca cadena de texto
     frmServidor.append(ip[0]);
     frmServidor.append(ip[1]);
     frmServidor.append(ip[2]);
     frmServidor.append(ip[3]);
     frmServidor.append("\n ");
     frmServidor.append(puerto);
     frmServidor.addCommand(cmdVolver);                    // Coloca el comando Salida
// * Metodos *
public void startApp() {
     sscInicio.hilo = true;                                   // Habilita el hilo
     new Thread(sscInicio).start();                         // Hilo en Canvas
     sscInicio.setCommandListener(this);                    // Define la forma que escucha comandos
     display.setCurrent(sscInicio);                         // Define objeto a mostrar
// Metodos comunes en todos los Midlet
public void pauseApp() {
     System.out.println("*** Pausado ***");
     sscInicio.hilo = false;                                   // Detiene el hilo
public void destroyApp(boolean unconditional) {
public void salir() {
     sscInicio.hilo = false;
     System.out.println("*** Terminado ***");
     destroyApp(false);                                        // Destruir objetos
     notifyDestroyed();                                        // Salir de la aplicacion
String cargarIP() {
String cadena;
// Cargar la direccion del servidor
     try {
          rsDireccion = RecordStore.openRecordStore("ipRecordStore", true );     // Crear si no existe
     } catch (Exception error) {}
     try {
          byte[] byteOutputData = rsDireccion.getRecord(1);     // Lee el primer registro
          cadena = new String(byteOutputData);
          System.out.println("Cargada: " + cadena);
     } catch (Exception error) {
          cadena = "190.65.161.158:24300";
     try {
          rsDireccion.closeRecordStore();                         // Cerrar
     } catch (Exception error) {}
     return cadena;
void guardarIP (String cadena) {
// Almacenar la direcci�n ip y puerto
     try {
          RecordStore.deleteRecordStore("ipRecordStore");     // Borrar si existe
     } catch (Exception error) {}
     try {
          rsDireccion = RecordStore.openRecordStore("ipRecordStore", true );     // Crear si no existe
     } catch (Exception error) {}
     try {
          byte[] byteOutputData = cadena.getBytes();     // Almacena los datos
          rsDireccion.addRecord(byteOutputData, 0, byteOutputData.length);
          System.out.println("Guardada: " + cargarIP());     // rsDireccion.getNumRecords()
     } catch (Exception error) {}
     try {
          rsDireccion.closeRecordStore();                    // Cerrar
     } catch (Exception error) {}
void mostrarIP(String cadena) {
int i, j=0, k;
     for (k=0; k<=2; k++) {
          i = cadena.indexOf('.', j);                         // Posicion del punto
          if (i < 0) {
               ip[k].setString("0");                         // Si hay error coloca 0
          } else {
               ip[k].setString(cadena.substring(j, i)); // Extrae direccion
          j = i + 1;
     i = cadena.indexOf(':', j);                              // Posicion del punto
     ip[3].setString(cadena.substring(j, i));          // Extrae direccion
     i = cadena.lastIndexOf(':');                         // Posicion dos puntos
     puerto.setString(cadena.substring(i+1));               // Extrae puerto
public void commandAction(Command c, Displayable s) {
     if (c == cmdEntrada) {
          if (sscInicio.img == sscInicio.ts) {          // Configurar servidor
               sscInicio.hilo = false;
               direccion = cargarIP ();                    // Cargar del record
               mostrarIP(direccion);                         // Mostrar en la forma
               System.out.println("*** OK ***");
               frmServidor.setCommandListener(this);
               display.setCurrent(frmServidor);
          } else {
               sscInicio.entrada = true;                    // Tiquete entrada
               AlertType.ERROR.playSound(TS_Online.display);     // Sonido
     } else if (c == cmdSalida) {
          sscInicio.entrada = false;                         // Tiquete salida
          AlertType.ERROR.playSound(TS_Online.display);     // Sonido
     } else if (c == cmdVolver) {                         // Volver a la pantalla anterior
          direccion = ip[0].getString() + "." + ip[1].getString() + "."
               + ip[2].getString() + "." + ip[3].getString() + ":" + puerto.getString();
          guardarIP(direccion);                              //Almacenar en record
          sscInicio.setCommandListener(this);
          sscInicio.hilo = true;                              // Arranca el hilo
          new Thread(sscInicio).start();                    // Hilo en Canvas
          display.setCurrent(sscInicio);
          System.out.println(sscInicio.hilo);
// * Clase graficadora *
class SSCanvas extends Canvas implements Runnable {
private int sleepTime;                                        // Tiempo de retrazo
static public boolean entrada = true;                    // Tiquete de entrada
static public boolean hilo;                              // Continuar hilo
static public Image ts = null;                         // Contenedor imagen
static public Image rojo = null;                         // Contenedor imagenpri
static public Image verde = null;                         // Contenedor imagen
static public Image img = null;                         // Contenedor imagen
static public String mensaje = null;                    // Cadena de salida
static public String mensaje2 = "";                    // Cadena de salida Codigo de barras
MIDlet midlet;                                                  // Enlace al midlet inicial
CommConnection cc = null;                         // Conector para puerto
//SocketConnection sc = null;                    // Conector para red
//SocketConnection cc = null;                    // Conector para red
public SSCanvas(MIDlet m) {
     midlet = m;                                                  // Referencia al MIDlet iniciado
     // Cargamos las im�genes a usar
     try {
          ts = Image.createImage("/TicketShop.PNG");     // Procedimiento para cargar las imagenes
          rojo = Image.createImage("/Rojo.PNG");          // Procedimiento para cargar las imagenes
          verde = Image.createImage("/Verde.PNG");     // Procedimiento para cargar las imagenes
     } catch (IOException e) {}                              // Error si no encuentra las imagenes
     img = ts;                                                  // Imagen de bienvenida
     mensaje = "Conectando";
     mensaje2 = "";                                             // Mensaje de inicio
void iniciar() {
     img = ts;                                                  // Imagen de bienvenida
     // Tiempo de espera para configurar servidor
     for (sleepTime = 1;sleepTime <= 3; sleepTime++) {
          try {
               mensaje = mensaje + ".";                    // Mensaje de inicio
               repaint();                                        // Redibuja la pantalla
               serviceRepaints();                              // Espera que termine
               Thread.sleep(1000);
          } catch (InterruptedException e) {
               System.out.println(e.toString());
     mensaje = "Conectado!";
     img = verde;
     repaint();                                        // Redibuja la pantalla
     serviceRepaints();                              // Espera que termine
     sleepTime = 50;
     System.out.println("Iniciar");
void codigo() {
     try {
          System.out.println("Leyendo");
          CommConnection cc = (CommConnection)Connector.open("comm:com0;baudrate=9600");
          //cc = (SocketConnection)Connector.open("socket://127.0.0.1:24300");
          //int baudrate = cc.getBaudRate();
          InputStream ic  = cc.openInputStream();          // Entrada serial
          //OutputStream oc = cc.openOutputStream();
          StringBuffer sbCodigo = new StringBuffer();     // Cadena de diferentes tipos de datos
          int ch = 255;
          while(ch > 32) {
               ch = ic.read();
               //oc.write(ch);
               if (ch > 32)
                    sbCodigo.append((char)ch);
          mensaje2 = sbCodigo.toString();                    // Codigo de barras
          if (mensaje2.equals("2864634059CULIB")) {
               valido();
          } else {
               invalido();
          ic.close();                                             // Cierra las conexiones
          //oc.close();
          cc.close();
     } catch (Exception e) {
          Alert a = new Alert("Error!", e.toString(), rojo, AlertType.ERROR);
          a.setTimeout(Alert.FOREVER);                                   // Alerta hasta que oprima boton
          TS_Online.display.setCurrent(a);               // Despues de la alerta vuelve a Inicio
          try {
               Thread.sleep(5000);
          } catch (Exception x) {}
void valido() {
     img = verde;                                             // Imagen OK
     mensaje = "Tiquete OK";                                   // Tiquete valido
     AlertType.CONFIRMATION.playSound(TS_Online.display);     // Sonido
void invalido() {
     img = rojo;                                                  // Imagen OK
     mensaje = "Tiquete Inv�lido";                         // Tiquete valido
     AlertType.ERROR.playSound(TS_Online.display);     // Sonido
// thread que contiene el game loop
public void run() {
     System.out.println("*** Hilo arrancado ***");
     if (img == ts)
          iniciar();
     while (hilo) {
          //System.out.println("Hilo");
          // Leer codigo de barras
          codigo();
          // validar codigo de barras
          //validar();
          // Actualizar pantalla
          repaint();                                                  // Redibuja la pantalla
          serviceRepaints();                                        // Espera que termine
          try {
               Thread.sleep(sleepTime);
          } catch (InterruptedException e) {
               System.out.println(e.toString());
protected void keyPressed(int keyCode) {
mensaje = Integer.toString(keyCode);
//int action = getGameAction(keyCode);
     if ((keyCode == -8) || (keyCode == 42)) {               // Si presiona borrar o *
          AlertType.ERROR.playSound(TS_Online.display);     // Sonido
          ((TS_Online)midlet).salir();
     } else if (keyCode == -51 || keyCode == -52 || keyCode == -53) {
          AlertType.ERROR.playSound(TS_Online.display);     // Sonido
public void paint(Graphics g) {
     // Borrar la pantalla
     g.setColor(255,255,255);
     g.fillRect (0, 0, getWidth(), getHeight());
     // Coloca la imagen correspondiente
     g.drawImage (img, getWidth()/2, 20, Graphics.HCENTER|Graphics.TOP);
     // Poner texto
     Font fuente = Font.getFont (Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_MEDIUM);
     g.setFont(fuente);
     g.setColor(0,0,0);
     g.drawString(mensaje, getWidth()/2, getHeight()/2,Graphics.TOP|Graphics.HCENTER);
     g.drawString(mensaje2, getWidth()/2, 5,Graphics.TOP|Graphics.HCENTER);
}

Similar Messages

  • Non-static cannot be referenced from a static context - ?

    Hi, i understand (kinda) what the error means
    i think its saying that i cannot call a non-static method "bubbleSort"
    from the static method main (correct?)
    but i dont know how to fix it...
    do i make bubbleSort
    public static void bubbleSort???
    C:\jLotto\dataFile\SortNumbers.java:80: non-static method bubbleSort(int[]) cannot be referenced from a static context
              bubbleSort( a ); //sort the array into ascending numbers
    my code:
    import java.io.*;
    import java.util.*;
    public class SortNumbers
         public static void main( String args[]) throws IOException
          int num;
              int a[] = new int[7]; //an array for sorting numbers
              File inputFile = new File("C:\\jLotto\\dataFile\\outagain.txt");
              File outputFile = new File("C:\\jLotto\\dataFile\\sortedNum.txt");
            BufferedReader br = new BufferedReader( new FileReader( inputFile ));
          PrintWriter pw = new PrintWriter( new FileWriter( outputFile ));
          String line = br.readLine();
          while( line != null ){//reads a single line from the file
             StringBuffer buffer = new StringBuffer(31);          //create a buffer
             StringTokenizer st = new StringTokenizer( line," "); //create a tokenizer
             while (st.hasMoreTokens()){
                        // the first 4 tokens are id,month,day,ccyy, no sorting needed
                        // so they are simply moved into the buffer
                        for (int i =1; i<5; i++){
                             num = Integer.parseInt(st.nextToken());
                             buffer.append( num );
                             buffer.append( "|");
                        //tokens 5 to 11 need to be sorted into acending order
                        //so read tokens 5 to 11 into an array for sorting
                        for (int i =0; i<7; i++){
                             a[i] = Integer.parseInt(st.nextToken());
                     bubbleSort( a ); //sort the array into ascending numbers
                      //the array is sorted so read array back into the buffer
                      for ( int i = 0; i < a.length; i++ ){
                           buffer.append( a[ i ] );
                           buffer.append(  "|" ) ;
                   }//end of while st.hasMoreTokens
             //then write out the record from the stringBuffer
             pw.println( buffer );
             line = br.readLine();
          }//end of while != null
              br.close();
              pw.close();
         }//end of static main
       // sort the elements of an array with bubble sort
       public void bubbleSort( int b[] )
          int swapMade = 0; //if after one pass, no swaps were made - exit
          for ( int pass = 1; pass < ( b.length - pass) ; pass++ ) // passes reduced for speed
              for ( int i = 0; i < b.length - 1; i++ ) // one pass
                  if ( b[ i ] > b[ i + 1 ] )            // one comparison
                      swap( b, i, i + 1 );              // one swap
                      swapMade = 1;
                  }  // end of if
               } //end of one pass
             if (swapMade == 0) pass = 7; //no swaps, so break out of outter for loop
          }//end of passes, end of outter for loop
       }//end of bubblesort method
       // swap two elements of an array
       public void swap( int c[], int first, int second )
          int hold;  // temporary holding area for swap
          hold = c[ first ];
          c[ first ] = c[ second ];
          c[ second ] = hold;
       }   //end of swap
    }//end of class SortNumbers

    Static means
    when u run the program (a class), there is only one variabel / type in memory.
    ex static int a; //assume it's inside the aStaticClass
    mean no wonder how many u create object from this class, variabel a only have 1 in memory. so if u change a (ex a=1;) all instance of this aStaticClass will effected (because they share the same variabel).
    Try to read more at :
    http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html
    I hope this will help you....happy new year
    yonscun

  • Non-static method cannot be referenced from a static context....again sry

    Hey, I know you guys have probably seen a lot of these, but its for an assignment and I need some help. The error I'm getting is: non-static method printHistory() cannot be referenced from a static context. Here are the classes effected
    public class BankAccount {
    private static int nextAccountNumber = 1000;
    //used to generate account numbers
    private String owner; //name of person who owns the account
    private int accountNumber; //a valid and unique account number;
    private double balance; //amount of money in the account
    private TransactionHistory transactions; //collection of past transactions
    private Transaction transaction;
    //constructor
    public BankAccount(String anOwnerName){
    owner = anOwnerName;
    accountNumber = nextAccountNumber++;
    balance = 0.0;
    transactions = new TransactionHistory();
    //public String getOwner() {
    public void deposit(double anAmount ){
         balance=balance+anAmount;
         transaction=new Transaction(TransactionType.DEPOSIT,accountNumber,anAmount,balance);
         transactions.add(transaction);
    //public void withdraw(double anAmount){
    //public String toString() {
    ***public void printHistory(){
         TransactionHistory.printHistory();
    AND
    public class TransactionHistory {
    final static int CAPACITY = 6; //maximum number of transactions that can be remembered
    //intentionally set low to make testing easier
    private Transaction[] transactions = new Transaction[CAPACITY];
    //array to store transaction objects
    private int size = 0;
    //the number of actual Transaction objects in the collection
    public void add(Transaction aTransaction){
         if (size>5){
         transactions[0]=transactions[1];
         transactions[1]=transactions[2];
         transactions[2]=transactions[3];
         transactions[3]=transactions[4];
         transactions[4]=transactions[5];
         transactions[5]=aTransaction;     
         transactions[size]=aTransaction;
         size=size++;
    public int size() {
         return size;
    ***public void printHistory() {
         for(int i=0;i<6;i++){
              System.out.println(transactions);
    //public void printHistory(int n){
    The project still isn't finished, so thats why some code is commented out. The line with *** infront on it are the methods directly effected, I think. Any help would be great.

    In Java, static means "something pertaining to an object class". Often, the term class is substituted for static, as in "class method" or "class variable." Non-static, on the other hand, means "something pertaining to an actual instance of an object. Similarly, the term +instance+ is often substituted for +non-static+, as in "instance method" or "instance variable."
    The error comes about because static members (methods, variables, classes, etc.) don't require an instance of the object to be accessed; they belong to the class. But a non-static member belongs to an instance -- an individual object. There's no way in a static context to know which instance's variable to use or method to call. Indeed, there may not be any instances at all! Thus, the compiler happily tells you that you can't access an instance member (non-static) from a class context (static).
    ~

  • Non-static method paint cannot be referenced from static context

    i cant seem to figure out this error dealing method paint:
    public class TemplateCanvas extends Canvas implements Runnable {
        //static
        public static final int STATE_IDLE      = 0;
        public static final int STATE_ACTIVE    = 1;
        public static final int STATE_DONE      = 2;
        private int     width;
        private int     height;
        private Font    font;
        private Command start;   
        private int state;
        private String message;
        public TemplateCanvas() {
            width = getWidth();
            height = getHeight();       
            font = Font.getDefaultFont();
            //// set up a command button to start network fetch
            start = new Command("Start", Command.SCREEN, 1);
            addCommand(start);
        public void paint(Graphics g) {
            g.setColor(0xffffff);
            g.fillRect(0, 0, width, height);
            g.setColor(0);
            g.setFont(font);
            if (state == STATE_ACTIVE) {
                Animation.paint(g);
            } else if (state == STATE_DONE) {
                g.drawString(message, width >> 1, height >> 1, Graphics.TOP | Graphics.HCENTER);
        public void commandAction(Command c, Displayable d) {
            if (c == start) {
                removeCommand(start);
                //// start fetching in a new thread
                Thread t = new Thread(this);
                t.start();
        public void run() {
            state = STATE_ACTIVE;
            //// start network fetch
            Network network = new Network();
            network.start();
            //// start busy animation
            Animation anim = new Animation(this);
            anim.start();
            //// wait for network to finish
            synchronized (network) {
                try {
                    wait();
                } catch (InterruptedException ie) { }
            //// end animation
            anim.end();
            //// get message from network
            message = network.getResult();
            //// repaint message
            state = STATE_DONE;
            repaint();
    }TemplateCanvas.java:38: non-static method paint(javax.microedition.lcdui.Graphics) cannot be referenced from a static context

    Animation.paint(g); paint() is not a static method. That means you have to call it on an instance of an Animation class (an object), not on the class itself. This is designed this way because the paint() method uses variables that have to be instantiated, so if you don't have an instance to use, it can't access the variables it needs. Static methods don't use instance variables, they only use what's passed in to them, so they don't need to be called on an object. Hope that was clear.

  • Non-static method getRealPath cannot be referenced from a static context

    Hi, I'm fairly new to java and servlets, I get the following error referencing the line denoted in the code snippet with a ">>" I don't understand why I am getting this error message?
    Message: non-static method getRealPath(java.lang.String) cannot be referenced from a static context
    public class events extends HttpServlet implements SingleThreadModel {
      private static final String CONTENT_TYPE = "text/html";
      //Initialize global variables
      public Document xmlDocument;
      public HttpSession theSession;
      public RequestDispatcher pageInit;
      public RequestDispatcher pageHeader;
      public RequestDispatcher pageFooter;
      public String path;
      public void setPath(){
    path = getServletContext.getRealPath( "/" );  }
      public void init() throws ServletException {
      }

    Ok More Code, I am weary of posting too much? I don't know why come to think of it?
    package altitude;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    import org.jdom.*;
    import altitude.sysVar;
    public class events extends HttpServlet implements SingleThreadModel {
      private static final String CONTENT_TYPE = "text/html";
      //Initialize global variables
      public Document xmlDocument;
      public HttpSession theSession;
      public RequestDispatcher pageInit;
      public RequestDispatcher pageHeader;
      public RequestDispatcher pageFooter;
      public String path;
      public void getRealPath(){
        path = ServletContext.getRealPath( "/" );
      public void init() throws ServletException {
      //Process the HTTP Get request
      public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
        //Initialise some Global Variables
        theSession = request.getSession( true );
        doPage( request, response );
      //Process the HTTP Post request
      public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
        //Initialise some Global Variables
        theSession = request.getSession( true );
        doPage( request, response );
    public void doPage( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
        //Initialise the variables and get the parameters from the query string.
        String eventID = request.getParameter( "eventID" );
        String dateFrom = request.getParameter( "dateFrom" );
        String dateTo = request.getParameter( "dateTo" );
        theSession.setAttribute( "Page Title", sysVar.servletTitle_events);
        Calendar theCalendar = Calendar.getInstance();
        RequestDispatcher pageInit = request.getRequestDispatcher( sysVar.servlet_initSession );
        pageInit.include( request, response );
        RequestDispatcher pageHeader = request.getRequestDispatcher( theSession.getAttribute( "Skin Directory" ) + sysVar.page_header );
        RequestDispatcher pageBody = request.getRequestDispatcher( sysVar.servletJsp_events );
        RequestDispatcher pageFooter = request.getRequestDispatcher( theSession.getAttribute( "Skin Directory" ) + sysVar.page_footer );
        //Initailize the site for this visitor this sets up the skin, and any customisations that may exist.
        //load variables, objects in to the session
        theSession.setAttribute( "Xml Document Object",  path + sysVar.data_events );
        pageHeader.include( request, response );
        pageBody.include( request, response );
        pageFooter.include( request, response );
        //remove the variables and the objects from the session
        theSession.setAttribute( "Xml Document Object", "" );
      //Clean up resources
      public void destroy() {
    }

  • Non-static method getIDnumber() cannot be referenced from a static context

    Student.java
    public class Student
         private int IDnumber;
         private int hours;
         private int points;
         public Student()
       IDnumber = 9999;
       points = 12;
       hours = 3;
         public void setIDnumber(int number)
         IDnumber = number;
       public int getIDnumber()
         return IDnumber;
       public void setHours(int number)
       hours = number;
       public int getHours()
       return hours;
       public void setPoints(int number)
       points = number;
       public int getPoints()
       return points;
         public void showIDnumber()
       System.out.println("ID Number is " + IDnumber);
       public void showHours()
       System.out.println("Credit Hours are " + hours);
       public void showPoints()
       System.out.println("Points Earned are " + points);
       public double getGradePoint()
       return (double) (points / hours);
    ShowStudent.java
    public class ShowStudent
         public static void main(String[] args)
              Student learner = new Student();
              int IDnumber;
              int points;
              int hours;
              IDnumber = Student.getIDnumber();
              points = Student.getPoints();
              hours = Student.getHours();
              System.out.println("ID number is " + IDnumber);
              System.out.println("Hours are " + hours);
              System.out.println("Points are " + points);
    Here I get the following.  How do I fix this?  Thanks.
    ShowStudent.java:9: non-static method getIDnumber() cannot be referenced from a
    static context
    IDnumber = Student.getIDnumber();
    ^
    ShowStudent.java:10: non-static method getPoints() cannot be referenced from a
    static context
    points = Student.getPoints();
    ^
    ShowStudent.java:11: non-static method getHours() cannot be referenced from a s
    tatic context
    hours = Student.getHours();
    ^
    3 errors

    You have to get the ID number of a particular instance i.e. IDnumber = learner.getIDnumber();

  • Non-static method getPerimeter() cannot be referenced from a static context

    I am getting this error message. I assume it is because getArea( ) and getPerimeter( ) are nonstatic and main is static? Can somebody help me? Thanks in advance!
    Error messages:
    non-static method getArea() cannot be referenced from a static context
              System.out.println("\nArea: " + onePlace.format(getArea()));
    non-static method getPerimeter() cannot be referenced from a static context
              System.out.println("Perimeter: " + onePlace.format(getPerimeter()));
    import java.util.Scanner;
    import java.text.DecimalFormat;
    public class Rectangle
         public double length;
         public double width;
         public Rectangle()
              length = 0;
              width = 0;
         public double getLength()
              return length;
         public double getWidth()
              return width;
         public void setLength(double length)
              this.length = length;
         public void setWidth(double width)
              this.width = width;
         public double getArea()
              return (length * width);
    /*     public double area(Rectangle R)
              double area = length * width;
              return area;
         public double getPerimeter()
              return ((length * 2) + (width * 2));
    /*     public double perimeter(Rectangle R)
              double perimeter = (length * 2) + (width * 2);
              return perimeter;
    /*     public String toString()
              double area = 0;
              double perimeter = 0;
              return "Area: " + area + "\tPerimeter: " + perimeter;
         public static void main(String [] args)
              DecimalFormat onePlace = new DecimalFormat("#0.0");
              Rectangle R = new Rectangle();
              Rectangle L = new Rectangle();
              Rectangle W = new Rectangle();
              Scanner input = new Scanner(System.in);
              System.out.println("Enter length of rectangle: ");
              L.setLength(input.nextDouble());
              System.out.println("\nEnter width of rectangle: ");
              W.setWidth(input.nextDouble());
              System.out.println("\nArea: " + onePlace.format(getArea()));
              System.out.println("Perimeter: " + onePlace.format(getPerimeter()));
    //          System.out.println(R.toString());
    }

    For some reason, something isn't being read.
    This is what I get:
    Enter length of rectangle:
    2
    Enter width of rectangle:
    4
    Area: 0.0
    Perimeter: 0.0
    Press any key to continue . . .
    Is it what I have to scan the input (L.setLength...)?
         public static void main(String [] args)
              DecimalFormat onePlace = new DecimalFormat("#0.0");
              Rectangle R = new Rectangle();
              Rectangle L = new Rectangle();
              Rectangle W = new Rectangle();
              Scanner input = new Scanner(System.in);
              System.out.println("Enter length of rectangle: ");
              L.setLength(input.nextDouble());
              System.out.println("\nEnter width of rectangle: ");
              W.setWidth(input.nextDouble());
              System.out.println("\nArea: " + onePlace.format(R.getArea()));
              System.out.println("Perimeter: " + onePlace.format(R.getPerimeter()));
    //          System.out.println(R.toString());
    }

  • Non-static method getContentPane() cannot be referenced from a static conte

    From this line I'm getting an error
    Container bmC = getContentPane();
    - non-static method getContentPane() cannot be referenced from a static context
    Aprecciate solution,
    thx

    The reason this is happening is that you can't call non-static methods from a static method. Non-static methods need an instance in order to be called. Static methods are not associated with an instance.

  • Non-static method close() cannot be referenced from a static context

    Friends,
    I am having a little help with some static and not static issues.
    I created a JMenuBar, it's in the file: SlideViewMenu.java
    One of the operations is File->Close and another is File->Exit.
    The listener is in the SlideViewMenu.java file. The listener needs to reference two non-static methods within SlideView.java.
    Here's some of the code:
    SlideViewMenu.java
    public class SlideViewMenu {
        public JMenuBar createMenuBar() {
        final Action openAction = new OpenAction();
        Action aboutAction = new AboutAction();
        ActionListener menuListener = new MenuActionListener();
        JMenuBar menuBar = new JMenuBar();
         // All the menu stuff works fine and is taken care of here.
       // Listener for Menu
       class MenuActionListener implements ActionListener {
         public void actionPerformed (ActionEvent actionEvent) {
              String selection = (String)actionEvent.getActionCommand();
             if (selection.equals("Close"))
              SlideViewFrame.close();
             else  SlideViewFrame.exit();
    }SlideView.java
    // Driver class
    public class SlideView {
         public static void main(String[] args) {
              ExitableJFrame f = new SlideViewFrame("SlideView");
                    // Stuff here, works fine.
    // Frame class
    class SlideViewFrame extends ExitableJFrame {
            // some things here, work fine.
         private SlideViewMenu menuBar = new SlideViewMenu();
         public SlideViewFrame(String title) {
         // Set title, layout, and background color
         super(title);
         setJMenuBar(menuBar.createMenuBar());
            // Stuff here works fine.
         // Handles doing stuff once the file has been selected
         public void setFileName(File fullFileName, String simpleName) {
            // Stuff here works fine.     
         // File->Close. clean up everything.
         public void close() {
              setTitle("SlideView");
              textArea.setText("");
              scrollBar.setVisible(false);
              textArea.setVisible(false);
              statsPanel.setVisible(false);
         // File->Exit.     
         public void exit() {
              System.exit(0);
    }The error I'm getting is:
    SlideViewMenu.java:50: non-static method close() cannot be referenced from a static context
    I don't get it?
    Thanks for all help.

    Making close() and exit() static would not solve the problem because close() requires access to nonstatic member variables/functions.
    Fortunately, that is not necessary. The real reason you are having a problem is that you don't have any way in your listener to access the main frame window, which is what the listener trying to control. You made a stab at gaining access by prefixing the function with the class name, but, as the compiler has informed you, that is only valid for static methods. If you think about it, you should see the sense in that, because, what if you had a number of frames and you executed className.close()? Which one would you close? All of them?
    Fortunately, there is an easy way out that ties the listener to the frame.
    SlideViewMenu.java:public class SlideViewMenu
      // Here's where we keep the link to the parent.
      private SlideViewFrame parentFrame;
      // Here's where we link to the parent.
      public JMenuBar createMenuBar(SlideViewFrame linkParentFrame)
        parentFrame = linkParentFrame;
        final Action openAction = new OpenAction();
        Action aboutAction = new AboutAction();
        ActionListener menuListener = new MenuActionListener();
        JMenuBar menuBar = new JMenuBar();
        // All the menu stuff works fine and is taken care of here.
      // Listener for Menu --- It is assumed that this is a non-static nested
      // class in SlideViewMenu. All SlideViewMenu variables are accessible from
      // here. If this is not the case, simply add a similar member variable
      //  to this class, initialize it with a constructor parameter, and
      // pass the SlideViewMenu parentFrame when the listener is
      // constructed.
      class MenuActionListener implements ActionListener
        public void actionPerformed (ActionEvent actionEvent)
          String selection = (String)actionEvent.getActionCommand();
          // Use parentFrame instead of class name.
          if (selection.equals("Close"))
              parentFrame.close();
            else
              parentFrame.exit();
    }SlideView.java// Driver class
    public class SlideView
      public static void main(String[] args)
        ExitableJFrame f = new SlideViewFrame("SlideView");
        // Stuff here, works fine.
    // Frame class
    class SlideViewFrame extends ExitableJFrame
      // some things here, work fine.
      private SlideViewMenu menuBar = new SlideViewMenu();
      public SlideViewFrame(String title)
        // Set title, layout, and background color
        super(title);
        //Here's where we set up the link.
        setJMenuBar(menuBar.createMenuBar(this));
      // Stuff here works fine.
      // Handles doing stuff once the file has been selected
      public void setFileName(File fullFileName, String simpleName)
        // Stuff here works fine.     
      // File->Close. clean up everything.
      public void close()
        setTitle("SlideView");
        textArea.setText("");
        scrollBar.setVisible(false);
        textArea.setVisible(false);
        statsPanel.setVisible(false);
      // File->Exit.
      public void exit()
        System.exit(0);
    }

  • Non-static method cannot be referenced from a static context

    Hey
    Im not the best java programmer, im trying to teach myself, im writing a program with the code below.
    iv run into a problem, i want to call the readFile method but i cant call a non static method from a static context can anyone help?
    import java.io.*;
    import java.util.*;
    public class Trent
    String processArray[][]=new String[20][2];
    public static void main(String args[])
    String fName;
    System.out.print("Enter File Name:");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    fName="0";
    while (fName=="0"){
    try {
    fName = br.readLine();
    System.out.println(fName);
    readFile(fName);
    catch (IOException ioe)
    System.out.println("IO error trying to read File Name");
    System.exit(1);
    public void readFile(String fiName) throws IOException {
    File inputFile = new File(fiName); //open file for reading
         FileReader in = new FileReader(inputFile); //
    BufferedReader br = new BufferedReader(
    new FileReader(inputFile));
    String first=br.readLine();
    System.out.println(first);
    StringTokenizer st = new StringTokenizer(first);
    while (st.hasMoreTokens()) {
    String dat1=st.nextToken();
    int y=0;
    for (int x=0;x<=3;){
    processArray[y][x] = dat1;
    System.out.println(y + x + "==" + processArray[y][x]);
    x++;
    }

    Hi am getting the same error in my jsp page:
    Hi,
    my adduser.jsp page consist of form with field username,groupid like.
    I am forwarding this page to insertuser.jsp. my aim is that when I submit adduser.jsp page then the field filled in form should insert into the usertable.The insertuser.jsp is like:
    <% String USERID=request.getParameter("id");
    String NAME=request.getParameter("name");
    String GROUPID=request.getParameter("group");
    try {
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewdatabase","root", "root123");
    PreparedStatement st;
    st = con.prepareStatement("Insert into user values (1,2,4)");
    st.setString(1,USERID);
    st.setString(2,GROUPID);
    st.setString(4,NAME);
    // PreparedStatement.executeUpdate();//
    }catch(Exception ex){
    System.out.println("Illegal operation");
    %>
    But showing error at the marked lines lines as:non static method executeupdate can not be referenced from static context.
    Really Speaking I am newbie in this java world.
    whether you have any other solution for above issue?
    waiting Your valuable suggestion.
    Thanks and regards
    haresh

  • "non-static variable cannot be referenced from a static contex"

    Hi, i'm writing a booking program at school and i'm getting 27 "non-static variable cannot be referenced from a static contex" errors. I can't find anything wrong with the code so I'm just asking you guys to look it through..
    public class bokningsmeny
    Bokning[] bokningslista = new Bokning[1000];
    String fornamn;
    String efternamn;
    String civilstand;
    String adress;
    String personnr;
    String telefonnr;
    int regnr;
    double inkomst;
    public static void main(String[] args)
    for(;;)
    System.out.println("\nMeny");
    System.out.println("________\n");
    System.out.println("1. Mata in nya personer.");
    System.out.println("2. S&ouml;k personen via personnummer och skriv personens andra uppgifter.");
    System.out.println("3. S&ouml;k personen via efternamn och skriv personens andra uppgifter.");
    System.out.println("4. S&ouml;k personen via personnummer och &auml;ndra adress.");
    System.out.println("5. S&ouml;k personen via personnummer och &auml;ndra telefonnummer.");
    System.out.println("6. S&ouml;k personen via personnummer och &auml;ndra civilst&aring;nd.");
    System.out.println("7. S&ouml;k personen vis personnummer och &auml;ndra inkomst");
    System.out.println("8. Skriv ut alla personer med givet namn.");
    System.out.println("9. Skriv ut alla personer med givet efternamn");
    System.out.println("10. Skriv ut alla personer med given adress");
    System.out.println("11. Skriv ut hela listan");
    System.out.println("12. Avsluta\n");
    int menyval = Keyboard.readInt();
    System.out.println("\n");
    switch(menyval)
    case 1:
    System.out.println("Mata in nya personer.\n______________________\n");
    boolean BOOuppgifter = false;
    for(int i = 0; i <= 1000; i++)
    if(bokningslista +== null)+
    +{+
    +SkrivInUppgifter();+
    +System.out.println("\nSt&auml;mmer informationen? (Y/N)");+
    +boolean BOOcase1yesorno = IsInputCorrect();+
    +if(BOOcase1yesorno == true)+
    +{+
    +System.out.println("\nBokningen lyckades!\n");+
    +bokningslista += new Bokning(fornamn, efternamn, civilstand, adress, personnr, telefonnr, regnr, inkomst);
    ++++else if(BOOcase1yesorno == false
    ++++System.out.println("\nBokningen avbruten.\n")
    ++++break
    ++++++break
    ++++case 2
    ++++System.out.println("Sok person med personnummer och &auml;ndra uppgifter.")
    ++System.out.println("___________________________________________________________\n")
    ++System.out.print("Skriv in sokord: ")
    ++String query = Keyboard.readString()
    ++query = query.toUpperCase()
    ++String personnummersok
    ++boolean contains
    ++int antal = 0
    ++boolean BOOcase2result = false
    ++System.out.println("Resultat: \n_________\n")
    ++for(int i = 0; i < 1000; i++
    ++++if(bokningslista +!<b<br />+<em<b<br />+++personnummersok = (bokningslista+.hamtaPersonnum()).t
    ++++contains = personnummersok.con
    ++++if(cont
    +<<br />++++BOOcase2r
    ++++ant
    ++++fornamn = bokningslist
    +++++efternamn = boknin
    ++++++personnr
    +++++++System.out.println(antal + ". " + fornam
    ++++<e<br />+++++++System.out.pri<br<br />+++++<em<br />+++++++System.out.println("\nVilket sokresultat vill du v&bdquo
    ++++<<br />+++++++if(case2ch
    +++++++System.ou
    +++<e<<br />+++<em<br />++++
    ++<em<br />+++++++System.out.p
    +++++<e<br />+++<<br<br /<br />+++++++System.out.printl
    +++<em<br />+++++<em<br />++
    <e<br />++++++++Sy
    +++++
    ++++++<e<br /><em<br />++++++++<<br />+++++<e<br />+++
    +++<<br />+++++++++else if(case11exit != 'y' &<br<br />+<<br />++++
    ++++
    +++++
    ++++<e<br />+++++++
    ++++<em<br />+++++
    +++<em<br />+++++<em<br />++++<<br />++++++
    ++++<e<br />+++++++<e<br />++<em<br />++++<e<br />+++<<br />+++++++++System.out.println("\n\nNamn: " + fornamn + "
    ++++++++++ "\nHemadress: " + adr
    ++++++++++ telefon
    +<<br />+++++++++Syste
    ++++<em<br />+++++++++if(correct
    <em<br />++<em<br />++<<br />++++<e<br /><<<br /><e<br />+++++++++I have another file with the Bokning.java class in it but I know for sure that its error free. Notice that I'm not nearly done with the program, theres like 10 more 'cases' to be created but I dont w
    ++<em</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Your code goes "+" crazy there, but here is your problem:
    public class B extends A {
        public void method() {}
        public static void main(String[] args) {
            //method(); //non-static method method() cannot be referenced from a static context
            B b = new B();
            b.method();
    }You need to be clear about the difference between static methods and non-static (instance) methods. Instance methods are applied to objects.

  • Another question: non-static variable super cannot be referenced from ...?

    class a
    int i;     
    int j=2;
    a(int i)
    this.i=i;
    public class b extends a
         b()
         super(8);     
    public static void main(String args[])
    b test=new b();
    System.out.print(test.i);
    test.j=1;
    System.out.print("test.j="+test.j);
    System.out.print("super.j="+super.j);
    b.java:28: non-static variable super cannot be referenced from a static context
    System.out.print("super.j="+super.j);
    ^
    1 error
    thanks

    You cannot call "super" from a static context. Just like you can't use "this" or call any non-static methods in a static context.
    Try with test.super.j, although I'm not sure if it works. But you can call super.j in a non-static context, e.g. in your constructor, or in a non-static method.

  • Non-static variable change cannot be referenced from a static context

    My compiler says: : non-static variable change cannot be referenced from a static context
    when i try to compile this. Why is it happening?
    public class change{
      int coin[] = {1,5,10,25,50};
      int change=0;
      public static void main(){
        int val = Integer.parseInt(JOptionPane.showInputDialog(null, "Type the amount: ", "Change", JOptionPane.QUESTION_MESSAGE));
        change = backtrack();
    }

    A static field or method is not associated with any instance of the class; rather it's associated with the class itself.
    When you declared the field to be non-static (by not including the "static" keyword; non-static methods and fields are much more common so it's the default), that meant that the field was a property of an object. But the static main method, being static, didn't have an object associated with it. So there was no "change" property to refer to.
    An alternative way to get this work, would be to make your main method instantiate an object of the class "change", and put the functionality in other instance methods.
    By the way, class names are supposed to start with upper-case letters. That's the convention.

  • "non-static ... cannot be referenced from a static..." BUT they're static!

    Well, this is starting to get a little frustrating.
    I compile and get "non-static method cannot be referenced from a static context", BUT I declared the method as static!!! Why am I still getting this!?!
    I'm calling the method from my main, as it is in another class. I've done this before and never ran into problems, but for some reason this time I am. Can anyone let me know what the problem could be and some possible solutions for fixing it.
    Thank you so much.

    A lot of people don't know this, but whenever you run javac or use a compiler in an IDE, it doesn't actually compile the code. It just packages it up and emails it to an email address at sun.com. There, a Sun developer reads your code and then turns it into bytecode by hand. It seems to go really fast, but that's because it's sent to to hundreds of offshore developers working in parallel. Then the lead developer emails your compiled class file back to javac, which then writes it to disk, unless the developer there had problems, in which case they email you back a list of error messages that javac displays to the screen.
    So what happened was, the first time you compiled it, the offshore developers didn't like you personally, so they sent you error messages. But the second time you tried to compile it, they had changed shifts, and the new developers did like you, so they compiled your code.
    Your code didn't change, you didn't invoke javac differently, and your code and your skills as a developer are all flawless. It's just a matter of whether the folks doing the compiliation like you.

  • Non-static variable total cannot be referenced from a static context

    i am trying to write a program that uses the if-else statements and when i wrote my program i got "non-static variable total cannot be referenced from a static context" for three lines of my input.
    A:\Disks.java:20: non-static variable total cannot be referenced from a static context total = (10000 * .95 + ((diskCount - 10000) * .85));
    ^
    A:\Disks.java:22: non-static variable total cannot be referenced from a static context total = (diskCount * .95);
    ^
    A:\Disks.java:24: non-static variable total cannot be referenced from a static context System.out.print(total);
    ^
    Do you know what I did wrong?

    I apologise in advance for the general tone of this reply.....
    Ummm, let me think for a second... You referenced a non static
    variable from a static context. Yup, yup. That's it !
    If you can't figure this out, you really need to do a Java tutorial or
    buy a text book. Basically though, total is a member of some class
    and you are trying to use it from a static function. I bet you have
    something like:
    public class Test {
        public int total;
        // blah blah blah
        public static void main(String[] args) {
            // This won't work cos "total" is a member and we are static
            System.out.println(total);
            // This works cos now you have an instance to pull total
            // out of.
            Test t = new Total();
            System.out.println(t.total);
    }

Maybe you are looking for

  • BW- CRM MSA: Job is cancelled when Generic variant is used

    Hi Gurus, We are trying to download BW Reports on Mobile Sales App. The implementation is working perfect when we create variants in BW and then fetch data in CRM. But now we want to restrict data according to territory of the Mobile User. This is to

  • Error while clearing vendor account

    Dear Experts, While clearing the vendor F-44 we are getting the error FM invoice document could not be found, Fi custom114 when we checked this document , this is op upload vendor balance for this vendor, now how we will clear this vendor with this e

  • Error log table for LSMW-Direct input

    Can any one tell me , What is the table for storing the error messages in LSMW-Direct input? Regards, Nagesh

  • New windows on clicking items in standalone applications

    Can standalone applications have new windows as menu's opened by clicking on the blocks , which have a lot of data parameters to be changed. In case I do not want to keep those data parameters on the front panel of a standalone application . windows

  • Updated question: Both Mac & PC links possible??

    I apologize right away for posting a new topic with my updated question. But I realized I didn't phrase it right to get any help. The question is - is it possible make both Mac links and PC links available on one disk. They would be in separate chapt