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.
Similar Messages
-
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 errorsYou 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,
thxThe 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 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() {
} -
What does this mean. I know about static, but I don't understand why I get this so many times.
I try to do something pretty normal and this is what I get a lot of times. I mean: the main() method should be static right? Then what good is the main() method if you cannot let it do stuff for you like this:
public class Test extends JFrame
public Test
setSize( 100, 100 );
show();
public static main( String args[] )
Test window = new Test();
draw();
public void draw()
blablabla whatever I want to do, a lot of times I can't.....
}Why is this, what is the reason for Java to forbid this and what can I do about it?Your draw() method, since it isn't defined as static is considered by Java to be part of your Test object; hence, it can only be invoked in the context of an existing instance of your object. In other words, any Java program that wanted to use your draw() method would have to create an instance of your Test class using something likemyTest = new Test()Your main method, however, is something different. Since you want to execute your class as a program, the Java run-time environment needs to have standard starting point. This starting point is the main method. The problem is that the main method must be static, because the run-time environment cannot be expected to know beforehand the correct way to create an instance of your class so that non-static methods can be invoked. The drawback is that your main method can only directly access methods that are defined as static.
There are two possible solutions to this problem, and which of the two you want to use depends on the object-oriented nature of your program.
On the one hand, if your draw() method is closely tied to the object itself, if the draw() method is actually drawing your object or a part of it, it should be left as an instance method, and you should simpy use the instance of the object you created in your main method:public static main( String args[] )
Test window = new Test();
// maybe some code to generate something to draw???
window.draw();
}This is what I think you are trying to do.
On the other hand, if your draw() method was some kind of universal method that didn't depend in any way on the current configuration of your instance, you could simply define draw() as static at which point your main method (or a method in an external class) could invoke it directly, without a corresponding instance. But if you did that, the draw() method itself would only be able to access static variables and methods.
Doug -
Non-static method rff() cannot be referenced from a static context
I get the above error when compiling my program, can anybody see what the problem is and how to fix it? its at the readstr = rff(); part after the if (i==2)
import java.io.*;
import java.util.Vector;
public class PropertyRental
public static Vector v = new Vector();
public static String menu;
public static String pc, hn, mr, ua, readstr;
public static int i, ln;
public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public String rff()
String line="";
String data="";
try
BufferedReader br = new BufferedReader(new FileReader("properties.txt"));
line = br.readLine();
do// EOF condition
System.out.println(line);
data = data + " \n" + line;
//line = br.readLine();
while( (line=br.readLine()) != null);
catch(IOException ioe)
return data;
public static void main()
try
do
System.out.println("Welcome to your local Property Rental Company");
System.out.println("You now have the following options");
System.out.println("");
System.out.println("1. Add a Property");
System.out.println("2. Remove a Property");
System.out.println("3. Display all Properties");
System.out.println("4. Exit the Program");
System.out.println("");
i = Double.valueOf(br.readLine()).intValue();
System.out.println("");
if(i == 1)
//BufferedWriter appends to properties.txt
//Our user input buffer
BufferedReader user = new BufferedReader(new InputStreamReader(System.in));
System.out.println("--- Add a Property ---");
//User enters address
System.out.println("\nEnter postcode (Must be less than 16 characters)");
pc = user.readLine();
//If the user has entered 'q' to quit, leave this loop
System.out.println("Enter house number");
hn = user.readLine();
System.out.println("Enter monthly rent");
mr = user.readLine();
//Write our details to file
v.addElement(new PropertyToLet(pc, hn, mr));
PrintWriter outFile;
try
outFile = new PrintWriter(new FileWriter("properties.txt" ,true));
PropertyToLet obj = (PropertyToLet) (v.lastElement());
outFile.println(obj.getpc() + "," + obj.gethn() + "," + obj.getmr());
outFile.close();
catch(IOException IOE)
System.err.println(IOE + "Has occured");
if(i == 2)
try
readstr = rff();
String[] splitArray = null;
splitArray = readstr.split(",");
for(int i=0;i<splitArray.length;i++)
if (v.size()<splitArray.length)
v.addElement(new PropertyToLet(splitArray[0], splitArray[1], splitArray[2])) ;
System.out.println("\nEnter the line number of the property you wish to remove");
int ln = Double.valueOf(br.readLine()).intValue();
v.removeElementAt(ln-1);
PrintWriter outFile = new PrintWriter(new FileWriter("properties.txt"));
for (int i=0; i<v.size(); i++)
PropertyToLet obj = (PropertyToLet) (v.lastElement());
outFile.println(obj.getpc() + "," + obj.gethn() + "," + obj.getmr());
outFile.close();
catch(Exception ex)
ex.printStackTrace();
if(i == 3)
String line="";
String data="";
try
BufferedReader br = new BufferedReader(new FileReader("properties.txt"));
line = br.readLine();
int counter=0;
do// EOF condition
counter++;
System.out.println(counter + ": " + line);
data = data + " \n" + line;
//line = br.readLine();
while( (line=br.readLine()) != null);
catch(IOException ioe)
if(i == 4)
//A simple instruction that tells the user how to exit the program
System.out.println("Press the 'x' button in the corner of the window to quit");
System.out.println("Do you want to exit [y/n]");
ua = br.readLine();
}while(ua.equals ("n"));
catch(IOException ioe)
}Edited by: Atomika3000 on Apr 23, 2009 4:09 AMYou must add modifier method to be static because you access the method from the main method which is a static method
public static String rff(){
// code
} I hope it helps you, good luck. -
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 setUp() cannot be referenced (error)
Hi;
I have this error
"findContainer.java": non-static method setUp() cannot be referenced from a static context at line 10, column 26
everytime i am trying to make this call
jade.core.AddContTry.setUp();in
public class findContainer {
public findContainer() {}
public void sUp(){
System.out.println("please wait, this is first try to find he agents in the main container"+"\n");
jade.core.AddContTry.setUp();
this setup() method
is written as follows
public void AddContTry () {
public void setUp(){
AID[] list= null;
try {
MyMainContainer = myprofile.getMain();
System.out.println("\n"+"This is the new container created in case of failure"+"\n");
list = MyMainCont.agentNames();
for (int i=0; i<list.length; i++){
System.out.println("names = " + list.toString() + " \n");
catch (ProfileException pe) { System.out.println("there is not main container");
could you please help me?My guess is that it is throwing a NullPointerException because you have not set 'a' to be anything.
The sample code you provided does not make sense.
AddContTry is a method in the code but you are using it like a class.
You have to set the following before you can use the object 'a'
AddContTry a = // something
I am just guessing here but can you write
AddContTry a = new AddContTry();
a.setUp();
Note, If this is the case, the code in setUp should be in the constructor. -
Cannot be referenced from a static context
im trying to link my user interface to the Game class to jump,
i get the error - non static method jump() cannot be referenced from a static context
private void jButton1_actionPerformed(ActionEvent e)
System.out.println("\njButton1_actionPerformed(ActionEvent e) called.");
// code
Game.jump();
any ideas? thanksah, it works if i change jump() to static
i was now wondering how to make the user interface
work with this ethod in the Game() class
private void goRoom(Command command)
if(!command.hasSecondWord()) {
// if there is no second word, we don't know where to go...
System.out.println("Go where?");
return;
String direction = command.getSecondWord();
// Try to leave current room.
Room nextRoom = currentRoom.getExit(direction);
if (nextRoom == null)
System.out.println("There is no door!");
else {
currentRoom = nextRoom;
System.out.println(currentRoom.getLongDescription());
i was thinking something like
private void jButton1_actionPerformed(ActionEvent e)
// code
Game.goRoom(Command north);
it doesnt seem to like that though.. :s -
Non static method cannot be referenced from a non static context
Dear all
I am getting the above error message in my program.
public void testing(Vector XY){
RecStore.checkUnits(XY);
}method checkUnits is non static and cannont be called from a non static context. I don't see the word static anywhere...
I have done a wider search throughout the main class and I'm haven't got any static their either.
Any ideas?
Thanks
DanYup
I had pared down my code, infact it is being called from within a large if statement.Irrelevant.
But the same thing still holds that there is no static keyword used.Read my previous post. Calling checkUnits using the class name:
RecStore.checkUnits(XY);implies a static context--in order for that call to work, checkUnits must be static. That's what your error message is saying--you are trying to call the non-static method "checkUnits" from the static context of using the class name "RecStore." -
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
thanksYou 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 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ök personen via personnummer och skriv personens andra uppgifter.");
System.out.println("3. Sök personen via efternamn och skriv personens andra uppgifter.");
System.out.println("4. Sök personen via personnummer och ändra adress.");
System.out.println("5. Sök personen via personnummer och ändra telefonnummer.");
System.out.println("6. Sök personen via personnummer och ändra civilstånd.");
System.out.println("7. Sök personen vis personnummer och ä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ä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 ä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. -
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.
Maybe you are looking for
-
HOW TO GET THE SELECTED VALUE IN A ROW FROM ONE VIEW TO ANOTHER VIEW?
hi all, I have a small issue. i have created two views.In the table of the first view i'm selecting a row and pressing the button it will move to next view. i am adding some fields manually in the table of the second view and pressing the save butto
-
Hi, I have a DT with Recordset (0..unbounded). using File content conversion converting xml to txt file. In CC parameters have used fieldFixedLengths and gave lengths. The source file is not placed in source directory. When checking in CC monitoring,
-
Purchased update to Flesh Builder 4.5
Got the email Thank you for registering. We invite you to update your member profile so that you can receive the latest and greatest information on Flash Builder from Adobe. You are also eligible to receive one of these benefits: 30 days of complimen
-
How to view 'Balanced Leaves'?
Hi Team, Could any one tell me 'How can I check the BALANCED LEAVES' for PL, SL etc. I gave the leaves 30 for PL and assigned quota 5 days, balanced 25 leaves should display (in 2006 or in pt50), but it is not showing the balanced leaves, it displays
-
My brand new charger broke off inside my iPad air...
ive had my iPad air for two years now and I've had every iPhone since the second one that came out... but all of a sudden the "high" quality charges that apple are offering obviously aren't of the quality they say. three brand new chargers I've boug