Non static variable?
i've a small problem with an object.
public class klassenobjekttest
public static void main(String[] args)
Auto meinFahrzeug;
meinFahrzeug = new Auto();
meinFahrzeug.name = "Porsche";
meinFahrzeug.erstzulassung = 1933; // woher soll ich das wissen?
meinFahrzeug.leistung = 300;
System.out.println("Fahrzeug name: " + meinFahrzeug.name);
System.out.println("Fahrzeug Erstzulassung: " + meinFahrzeug.erstzulassung);
System.out.println("Fahrzeug Leistung: " + meinFahrzeug.leistung);
class Auto
public String name;
public int erstzulassung;
public int leistung;
the sdk says:
klassenobjekttest.java:6: non-static variable this cannot be referenced from a s
tatic context
meinFahrzeug = new Auto();
^
1 error
what's wrong?
However if i use:
public class klassenobjekttest
Auto meinFahrzeug;//brought this line out of main
public static void main(String[] args)
meinFahrzeug = new Auto();
meinFahrzeug.name = "Porsche";
meinFahrzeug.erstzulassung = 1933; // woher soll ich das wissen?
meinFahrzeug.leistung = 300;
System.out.println("Fahrzeug name: " + meinFahrzeug.name);
System.out.println("Fahrzeug Erstzulassung: " + meinFahrzeug.erstzulassung);
System.out.println("Fahrzeug Leistung: " + meinFahrzeug.leistung);
class Auto
public String name;
public int erstzulassung;
public int leistung;
It does not work.
could somebody tell me why.
Appreciate the help
Thanks,
Preetham.
Similar Messages
-
Error on compile - non-static variable can not be referencedfrom static con
Error on compile happening with addButton?
Thanks
import java.awt.*;
import java.awt.event.*;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
public class Log implements ActionListener {
JButton addButton;
public static void addComponentsToPane(Container pane) {
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridy = 3;
c.gridx = 0;
JLabel callsignLabel= new JLabel("Callsign");
pane.add(callsignLabel, c);
c.gridy = 3;
c.gridx = 1;
JLabel nameLabel= new JLabel("Name");
pane.add(nameLabel, c);
c.gridy = 3;
c.gridx = 2;
JLabel timeLabel= new JLabel("Time");
pane.add(timeLabel, c);
c.gridy = 3;
c.gridx = 3;
JLabel dateLabel= new JLabel("Date");
pane.add(dateLabel, c);
c.gridy = 3;
c.gridx = 4;
JLabel frequencyLabel= new JLabel("Freq ");
pane.add(frequencyLabel, c);
c.gridy = 3;
c.gridx = 5;
JLabel locationLabel = new JLabel("Country/State");
pane.add(locationLabel, c);
c.gridy = 5;
c.gridx = 0;
addButton = new JButton("Add");
pane.add(addButton, c);
addButton.addActionListener(this);Thank you for the reply
I am new to Java
What is wrong with the way it is coded?The error message tells you what's wrong: You're trying to reference a non-static variable from a static context.
If you don't know what that means, then click the link I provided and look at the results from that google search. You might have to go through a few before you find a satisfactory explanation. And after you've done that, if you have specific questions about things you didn't understand there, please post again. -
Non-static variable Help needed
Hi, I am creating a multi threaded web server but get the following error
non-static variable this cannot be referenced from a static context
HttpRequest request = new HttpRequest(connectionSocket);
Please could someone help.
Many Thanks
import java.io.* ;
import java.net.* ;
import java.util.* ;
public final class MultiWebServer
public static void main(String argv[]) throws Exception
// Set the port number.
int port = 6789;
// Establish the listen socket.
String fileName;
ServerSocket listenSocket = new ServerSocket(port);
// Process HTTP service requests in an infinite loop.
while (true) {
// Listen for a TCP connection request.
Socket connectionSocket = listenSocket.accept();
// Construct an object to process the HTTP request message.
HttpRequest request = new HttpRequest(connectionSocket);
// Create a new thread to process the request.
Thread thread = new Thread(request);
// Start the thread.
thread.start();
final class HttpRequest implements Runnable
final static String CRLF = "\r\n";
Socket socket;
String requestMessageLine;
String fileName;
Date todaysDate;
// Constructor
public HttpRequest(Socket socket) throws Exception
this.socket = socket;
socket = null;
// Implement the run() method of the Runnable interface.
public void run()
try {
processRequest();
} catch (Exception e) {
System.out.println(e);
private void processRequest() throws Exception
// Get a reference to the socket's input and output streams.
//InputStream is = new InputStream(socket.getInputStream());
//DataOutputStream os = new DataOutputStream(socket.getOutputStream());
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(
socket.getInputStream()));
DataOutputStream outToClient =
new DataOutputStream(
socket.getOutputStream());
// Set up input stream filters.
requestMessageLine = inFromClient.readLine();
//BufferedReader br = null;
// Get the request line of the HTTP request message.
String requestLine = null;
// Display the request line.
System.out.println();
System.out.println(requestLine);
StringTokenizer tokenizedLine =
new StringTokenizer(requestMessageLine);
if (tokenizedLine.nextToken().equals("GET"))
fileName = tokenizedLine.nextToken();
if ( fileName.startsWith("/")==true )
fileName = fileName.substring(1);
File file = new File(fileName);
int numOfBytes = (int)file.length();
FileInputStream inFile = new FileInputStream(fileName);
byte[] fileInBytes = new byte[numOfBytes];
inFile.read(fileInBytes);
/* Send the HTTP header */
outToClient.writeBytes("HTTP/1.1 200 Document Follows\r\n");
if (fileName.endsWith(".jpg"))
outToClient.writeBytes("Content-Type: image/jpeg\r\n");
if (fileName.endsWith(".jpeg"))
outToClient.writeBytes("Content-Type: image/jpeg\r\n");
if (fileName.endsWith(".gif"))
outToClient.writeBytes("Content-Type: image/gif\r\n");
if (fileName.endsWith(".html"))
outToClient.writeBytes("Content-Type: text/html\r\n");
if (fileName.endsWith(".htm"))
outToClient.writeBytes("Content-Type: text/html\r\n");
outToClient.writeBytes("Content-Length: " + numOfBytes + "\r\n");
outToClient.writeBytes("\r\n");
/* Now send the actual data */
outToClient.write(fileInBytes, 0, numOfBytes);
socket.close();
else
System.out.println("Bad Request Message");
todaysDate = new Date();
try {
FileInputStream inlog = new FileInputStream("log.txt");
System.out.println(requestMessageLine + " " + todaysDate );
FileOutputStream log = new FileOutputStream("log.txt", true);
PrintStream myOutput = new PrintStream(log);
myOutput.println("FILE -> " + requestMessageLine + " DATE/TIME -> " + todaysDate);
catch (IOException e) {
System.out.println("Error -> " + e);
System.exit(1);
socket.close();import java.io.* ;
import java.net.* ;
import java.util.* ;
public final class MultiWebServer
public MultiWebServer(){
try{
// Set the port number.
int port=6789;
// Establish the listen socket.
String fileName;
ServerSocket listenSocket=new ServerSocket(port);
// Process HTTP service requests in an infinite loop.
while(true){
// Listen for a TCP connection request.
Socket connectionSocket=listenSocket.accept();
// Construct an object to process the HTTP request message.
HttpRequest request=new HttpRequest(connectionSocket);
// Create a new thread to process the request.
Thread thread=new Thread(request);
// Start the thread.
thread.start();
}catch(IOException ioe){
}catch(Exception e){
public static void main(String argv[]) throws Exception
new MultiWebServer();
final class HttpRequest implements Runnable
final static String CRLF = "\r\n";
Socket socket;
String requestMessageLine;
String fileName;
Date todaysDate;
// Constructor
public HttpRequest(Socket socket) throws Exception
this.socket = socket;
socket = null;
// Implement the run() method of the Runnable interface.
public void run()
try {
processRequest();
} catch (Exception e) {
System.out.println(e);
private void processRequest() throws Exception
// Get a reference to the socket's input and output streams.
//InputStream is = new InputStream(socket.getInputStream());
//DataOutputStream os = new DataOutputStream(socket.getOutputStream());
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(
socket.getInputStream()));
DataOutputStream outToClient =
new DataOutputStream(
socket.getOutputStream());
// Set up input stream filters.
requestMessageLine = inFromClient.readLine();
//BufferedReader br = null;
// Get the request line of the HTTP request message.
String requestLine = null;
// Display the request line.
System.out.println();
System.out.println(requestLine);
StringTokenizer tokenizedLine =
new StringTokenizer(requestMessageLine);
if (tokenizedLine.nextToken().equals("GET"))
fileName = tokenizedLine.nextToken();
if ( fileName.startsWith("/")==true )
fileName = fileName.substring(1);
File file = new File(fileName);
int numOfBytes = (int)file.length();
FileInputStream inFile = new FileInputStream(fileName);
byte[] fileInBytes = new byte[numOfBytes];
inFile.read(fileInBytes);
/* Send the HTTP header */
outToClient.writeBytes("HTTP/1.1 200 Document Follows\r\n");
if (fileName.endsWith(".jpg"))
outToClient.writeBytes("Content-Type: image/jpeg\r\n");
if (fileName.endsWith(".jpeg"))
outToClient.writeBytes("Content-Type: image/jpeg\r\n");
if (fileName.endsWith(".gif"))
outToClient.writeBytes("Content-Type: image/gif\r\n");
if (fileName.endsWith(".html"))
outToClient.writeBytes("Content-Type: text/html\r\n");
if (fileName.endsWith(".htm"))
outToClient.writeBytes("Content-Type: text/html\r\n");
outToClient.writeBytes("Content-Length: " + numOfBytes + "\r\n");
outToClient.writeBytes("\r\n");
/* Now send the actual data */
outToClient.write(fileInBytes, 0, numOfBytes);
socket.close();
else
System.out.println("Bad Request Message");
todaysDate = new Date();
try {
FileInputStream inlog = new FileInputStream("log.txt");
System.out.println(requestMessageLine + " " + todaysDate );
FileOutputStream log = new FileOutputStream("log.txt", true);
PrintStream myOutput = new PrintStream(log);
myOutput.println("FILE -> " + requestMessageLine + " DATE/TIME -> " + todaysDate);
catch (IOException e) {
System.out.println("Error -> " + e);
System.exit(1);
socket.close(); -
Non-static variable being used in static context
I am currently attempting to write a basic user login system using basic applets. I have two JTextFields named "userText" and "passText".
What i am attempting to do is use the ".getText()" method to get the text out of the JTextField and verifying the string against a string already in a file using the bufferedReader, etc.
However when i try to compare the string in the file with the one in the text field using the following code:
if ((line.compareTo(username)) == 0)
i get the following error...
"non-static variable being used in a static context"
Any ideas?The static method doesn't know about instances of the class instead you pass the instance to the method:
static public void myMethod(MyClass instance, String var) {
if(instance.line.compareTo(var))
And then the call would be:
MyClass.myMethod(anInstance, userName); -
Non-static variable cant accessed from the static context..your suggestion
Once again stuck in my own thinking, As per my knowledge there is a general error in java.
i.e. 'Non-static variable cant accessed from static context....'
Now the thing is that, When we are declaring any variables(non-static) and trying to access it within the same method, Its working perfectly fine.
i.e.
public class trial{
���������� public static void main(String ar[]){ ////static context
������������ int counter=0; ///Non static variable
������������ for(;counter<10;) {
�������������� counter++;
�������������� System.out.println("Value of counter = " + counter) ; ///working fine
�������������� }
���������� }
Now the question is that if we are trying to declare a variable out-side the method (Non-static) , Then we defenately face the error' Non-static varialble can't accessed from the static context', BUT here within the static context we declared the non-static variable and accessed it perfectly.
Please give your valuable suggestions.
Thanks,
JeffOnce again stuck in my own thinking, As per my
knowledge there is a general error in java.
i.e. 'Non-static variable cant accessed from static
context....'
Now the thing is that, When we are declaring any
variables(non-static) and trying to access it within
the same method, Its working perfectly fine.
i.e.
public class trial{
���������� public static void
main(String ar[]){ ////static context
������������ int counter=0; ///Non
static variable
������������ for(;counter<10;) {
�������������� counter++;
��������������
System.out.println("Value
of counter = " + counter) ; ///working fine
�������������� }
���������� }
w the question is that if we are trying to declare a
variable out-side the method (Non-static) , Then we
defenately face the error' Non-static varialble can't
accessed from the static context', BUT here within
the static context we declared the non-static
variable and accessed it perfectly.
Please give your valuable suggestions.
Thanks,
JeffHi,
You are declaring a variable inside a static method,
that means you are opening a static scope... i.e. static block internally...
whatever the variable you declare inside a static block... will be static by default, even if you didn't add static while declaring...
But if you put ... it will be considered as redundant by compiler.
More over, static context does not get "this" pointer...
that's the reason we refer to any non-static variables declared outside of any methods... by creating an object... this gives "this" pointer to static method controller. -
Non-static variable from a static context
This is the error i get . If i understand the error correctly it says im using a static variable when i shouldnt be? Or is it the other way round? below the error is the actual code....
The error...
Googler.java:27: non-static variable this cannot be referenced from a static context
submitButton.addActionListener(new ButtonHandler());The code...
JButton submitButton = new JButton("Submit Query");
submitButton.addActionListener(new ButtonHandler());thanks for the response.
I have already tried what you said but I tried it again anyway and i get the same error more less...
Googler.java:28: non-static variable this cannot be referenced from a static context
ButtonHandler buttonHandler = new ButtonHandler();here is part of my code
public class Googler
static JTextField input1, input2;
public static void main(String[] args)
JFrame myFrame = new JFrame("Googler v1.0");
Container c = myFrame.getContentPane();
JLabel lab1 = new JLabel("Enter Google Query:");
JLabel lab2 = new JLabel("Enter Unique API Key:");
input1 = new JTextField(15);
input2 = new JTextField(15);
JRadioButton radSearch = new JRadioButton("Search Query");
JRadioButton radCached = new JRadioButton("Cached Query");
JButton submitButton = new JButton("Submit Query");
ButtonHandler buttonHandler = new ButtonHandler();
submitButton.addActionListener(buttonHandler);
ButtonGroup group = new ButtonGroup();
group.add(radSearch);
group.add(radCached);Ive tried declaring buttonHandler as a static variable and this dosn't work either. I've never had this problem before it must be something silly im missing...?
Thanks
Lee -
Non-static variable from static context?
Hi,
I've created a program using swing components
and I've set up a addActionListener to a button,
button.addActionListener(this);
when try and compile I get the following error:
non-static variable this cannot be referenced from a
static context
button.addActionListener(this);
I've checked site and my notes I don't seem to have
done anything different from programs that have compiled
in the past.
I'm currently doing a programming course so I'm fairly
new to Java, try not to get to advanced on me :)
Thx in advance for any help.
ChrisWell what is declared static? If I remeber right this error means that you have a static method that is trying to access data it does not have access to. Static methods cannot access data that is intance data because they do not exist in the instance (not 100% sure about this but I believe it is true, at the very least I know they do not have access to any non-static data). Post some more of your code like where you declare this (like class def) and where you set up the button.
-
Non static variable in static context
import java.util.Scanner;
public class project4_5 {
int die1, die2;
int comptotal = 0, playertotal = 0, turntotal = 0;
int turn, comprun = 0;
String playername;
String action = ("R");
Scanner scan = new Scanner(System.in);
public static void main (String[] args)
PairOfDice mydie = new PairOfDice();
System.out.println("!!!!!!PIG!!!!!!");
System.out.println();
System.out.println("Enter your name! ");
playername = scan.nextLine();
while(playertotal>100 && comptotal>100){
while(action.equalsIgnoreCase("R")){
System.out.println(playername+" roll or pass the die (R/P) ");
action = scan.nextLine();
if(action.equalsIgnoreCase("P"))
break;
mydie.roll();
die1 = mydie.getFace1();
die2 = mydie.getFace2();
System.out.println("You rolled a "+die1+" and a "+ die2);
if(die1==1||die2==1){
turntotal = 0;
System.out.println("You rolled a 1, you lose your points"
+" for this turn.");
break;
else if(die1==1&&die2=1){
playertotal = 0;
System.out.println("You rolled snake eyes, all points have"
+ " been lost.");
break;
else
turntotal= turntotal+die1+die2;
System.out.println("Would you like to roll or pass? (R/P)");
if(action.equalsIgnoreCase("P")){
playertotal = playertotal+turntotal;
turntotal = 0;
while(turntotal<=20||turns!=run){
turn = (int) (Math.random() * 5 + 1);
mydie.roll();
die1 = mydie.getFace1();
die2 = mydie.getFace2();
System.out.println("Computer rolled a "+die1+
" and a "+ die2);
if(die1==1||die2==1){
turntotal = 0;
System.out.println("Computer rolled a 1 he loses hi points"
+" for this turn.");
break;
else if(die1==1&&die2=1){
playertotal = 0;
System.out.println("Computer rolled snake eyes, his points have"
+ " been lost.");
break;
else
turntotal= turntotal+die1+die2;
comprun++;
turntotal = 0;
}here is code for a dice game i made...and when i compile it practically every variable gets an error saying non-static variable can not be referenced from a static context....anyone kno what this means or how i go about fixing it...i think it has something to do with assigning the return variable from my getFace method to die1 and die 2...idk how to fix it tho
if u need it my die class is below
public class PairOfDice
int faceValue1, faceValue2;
public PairOfDice()
faceValue1 = 1;
faceValue2 = 1;
public void roll()
faceValue1 = (int) (Math.random() * 6 + 1);
faceValue2 = (int) (Math.random() * 6 + 1);
public int getFace1 ()
return faceValue1;
public int getFace2 ()
return faceValue2;
It means what it says -- that you're trying to use a non-static thing (like a method or a field) from a static thing (like your main method).
You can either make everything static (which isn't great -- it flies in the face of object-oriented programming) or instantiate an object.
If you want to do the latter, then try this: make your main method instantiate a method, and run it, like this:
public static void main(String[] argv) {
project4_5 game = new project4_5();
game.play();
}Then create a method called play:
public void play() {
// put everything that's currently in main() in here
}See if that fixes it for you. -
Help me please~ non-static variable rs cannot be referenced ...
i make counter
but this error occurrence
only i doing resultset make and closed
why non-static variable rs ....
i am sorry i don't speak English ...
help me please..
error message
non-static variable rs cannot be referenced from a static context
source
===============================================
package jjaekim;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Count{
Statement stmt;
ResultSet rs;
ResultSet rs2;
Connection conn;
//DBPoolManager dbpm;
public static String add(HttpServletRequest request){
try{
int year =0;
int month=0;
int date =0;
int hour =0;
int min =0;
int week =0;
String str_date=new String();
String str_time=new String();
String referer_url =request.getHeader("Referer");
String infomation =request.getHeader("User-Agent");
String ip =request.getRemoteAddr();
int access_date=0;
int access_time=0;
Calendar cal =Calendar.getInstance();
year =cal.get(cal.YEAR);
month =cal.get(cal.MONTH) + 1;
date =cal.get(cal.DATE);
hour =cal.get(cal.HOUR_OF_DAY);
min =cal.get(cal.MINUTE);
week =cal.get(cal.DAY_OF_WEEK);
access_date =(month*100)+date;
access_time =(hour*100)+min;
if(access_date<1000)
str_date="0"+new Integer(access_date).toString();
else
str_date=new Integer(access_date).toString();
if(access_time<100)
str_time="0"+new Integer(access_time).toString();
else
str_time="0"+new Integer(access_time).toString();
}catch(Exception e){
//System.out.print("Exc"+e.getMessage());
//return false;
finally{
if(rs!=null){
try{ rs.close();}catch(Exception e){}
if(rs2!=null){
try{ rs2.close();}catch(Exception e){}
if (stmt!=null){
try{ stmt.close();}catch(Exception e){}
//if (conn!=null){
try{ conn.close(); }catch(Exception e){}
//return back;
/* public static void main(String[] args)
System.out.println("Hello World!");Hello jjaekim,
if rs is a class variable (the same value for all objects),
try this (more likely to be the right solution) :
static ResultSet rs;
instead of :
ResultSet rs;
if rs has a different values in different objects,
then you should add the object name when using it like this :
myObject.rs or this.rs -
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 addressed to Static Variable
Hi,
I am new to java, I am getting (Non Static Variable sb,serverAddress addressed to Static Variable)
Here is the code. Thanks for reading, any help or explanation would be appreciated-
* To change this template, choose Tools | Templates
* and open the template in the editor.
package webcheck;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
* @author
public class checkhttp {
private URL serverAddress = null;
private StringBuilder sb = null;
public checkhttp(java.net.URL serverAddress,java.lang.StringBuilder StringBuilder)
this.serverAddress=serverAddress;
this.sb=sb;
public static void main(String[] args) {
HttpURLConnection connection = null;
OutputStreamWriter wr = null;
BufferedReader rd = null;
String line = null;
int x;
//checkhttp check= new checkhttp();
try {
serverAddress = new URL("http://www.yahoo.com");
//set up out communications stuff
connection = null;
//Set up the initial connection
connection = (HttpURLConnection)serverAddress.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setReadTimeout(10000);
connection.connect();
//get the output stream writer and write the output to the server
//wr = new OutputStreamWriter(connection.getOutputStream());
//wr.write("");
//wr.flush();
//read the result from the server
rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
sb = new StringBuilder();
while ((line = rd.readLine()) != null)
sb.append(line + '\n');
System.out.println(sb.toString());
System.out.println("Server is up");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
finally
//close the connection, set all objects to null
connection.disconnect();
//rd = null;
//sb = null;
//wr = null;
connection = null;
}Someone please correct me if I'm wrong, but since main is static, any fields it access must also be static.
The static keyword declares that something is accessable no matter the class state, thus you can call main() and run your program without having something make an instance of the object that your progam defines. For example:
class Foo {
static public String strText = "Hello World";
//Later in some method, this is valid.
String MyString = Foo.strText;
//However, if strText was not static you need to
Foo fooExample = new Foo();
String myString = fooExample.strText;Static should not override private, so static private fields/members are not accessable. To be accessable you still need to be public.
Edited by: porpoisepower on Jan 21, 2010 2:18 PM -
I have been working on this file for 4 days now and I can't get past these errors.
Here's the whole project:
package toysmanager;
public class ToysManager {
//Method ToysManager
public ToysManager() {
//Method main
public static void main(String[] args) {
ToddlerToy Train1 = new ToddlerToy();
ToddlerToy Train2 = new ToddlerToy();
ToddlerToy Train3 = new ToddlerToy();
System.out.print("This is an object of type ToysManager");
Train1.PrintProductID();
Train2.PrintProductID();
Train3.PrintProductID();
public class ToddlerToy{
private int ProductID = 0;
private String ProductName = "";
private float ProductPrice = 0;
public ToddlerToy(int id,String name, float price){
ProductID = id;
ProductName = name;
ProductPrice = price;
//Method PrintProductID
public int PrintProductID(){
System.out.print("This method is PrintProductID in the class ToddlerToy");
System.out.print("Product ID is:" + ProductID);
return ProductID;
public String PrintProductName(){
System.out.print("This method is PrintProductName in the class ToddlerToy");
System.out.print("Product Name:" + ProductName);
return ProductName;
public float PrintProductPrice(){
System.out.print("This method is PrintProductPrice in the class ToddlerToy");
System.out.print("Product Price: $" + ProductPrice);
return ProductPrice;
And here are the errors:
"ToysManager.java": non-static variable this cannot be referenced from a static context at line 9, column 29
"ToysManager.java": ToddlerToy(int,java.lang.String,float) in toysmanager.ToysManager.ToddlerToy cannot be applied to () at line 9, column 29
"ToysManager.java": non-static variable this cannot be referenced from a static context at line 10, column 29
"ToysManager.java": ToddlerToy(int,java.lang.String,float) in toysmanager.ToysManager.ToddlerToy cannot be applied to () at line 10, column 29
"ToysManager.java": non-static variable this cannot be referenced from a static context at line 11, column 29
"ToysManager.java": ToddlerToy(int,java.lang.String,float) in toysmanager.ToysManager.ToddlerToy cannot be applied to () at line 11, column 29
Any help would be appreciated as I am plainly not understanding this even with a book.Annie:
Could you help me understand the original ToyManager instructions more please? Not asking you to do the work for me I just do not understand exactly what they want me to do...
Assignment:
After you install JCreator, write a Java program, with a single class called ToysManager. The main method should print the name of the class, for example: "This is an object of type ToysManager."
(Hint: the process is very similar to the "Hello World!" program.)
Please add file (.java)
Group Portion:
Deliverables: two *.java files
As a group, add a second class called ToddlerToy to your ToysManager project.
Here are the requirements for the ToddlerToy:
* The class ToddlerToy is public and has a default constructor.
* It has one private attribute called ProductID (of type int).
* It has two public methods called SetProductId() and PrintProductId().
* The method SetProductId() assigns a value to the attribute ProductId. For now, the value is hard-coded.
* The method PrintProductId prints the value of the attribute ProductId.
* The class ToddlerToy has no main() method. In Java, there is only one main method for the entire program. In this case, the main method is in the ToysManager class.
Here are the requirements for the main method of the ToysManager class:
* Create an object called Train1 of class type ToddlerToy, using the default constructor.
* Call the methods SetProductId() and PrintProductId() to set then print the the value of ProductId.
* The first statement in each method should print the name of the method, for example: "This is method <method name> in class <class name>". This should help you trace the execution of your program. Feel free to comment out the print statement.
* On the Small Group Discussion Board, discuss your understanding of the concepts of class, object, constructor, method, and attribute.
* Give one example of a class (giving its name, attributes, and methods) that could be part of the shipping application.ANY help with this at all is greatly appreciated...a friend of mine found your post and used it to give me code snippets for help and I had no idea. Nearly got me in deep water...redoing the assignment but personally I find the next two assignments much easier to understand than this one. The instructions are confusing to me...can you point me in the right direction? -
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);
} -
Non-static variable aceYears cannot be referenced from a static context
This is my error...
investment.java:53: non-static variable aceYears cannot be referenced from a static context
lwInvest.numberAceYears(aceYears);
^
This is my code...
public static void main (String[] args)
investment.Invest.numberAceYears(aceYears);
and more code
String termInvested = JOptionPane.showInputDialog
("Please enter the amount of years to invest your investment.");
int intTermInvested = Integer.parseInt(termInvested);
and yet more code..
public void numberAceYears (int aceYears)
for (int aY = 5 ; aY <= aceYears; aY++)
double aceInterest = aceCoBalance * aceCoRate /100;
aceCoBalance = aceCoBalance + aceInterest;
aceYears = aceYears + aY;
Suggestions?Short version: Either make the variable in question static, or create an instance of your class and use that to access it. Either one will work, but one probably suits your design better. It's up to you to figure out which one.
For details, see the relevant section of your favorite Java book or tutorial, or poke around here:
http://www.google.com/search?q=java+non+static+variable+cannot+be+referenced+from+a+static+context
Maybe you are looking for
-
How to use MTO stock in MTS order.
Hi My client wants the MTO stock also to be be used in MTS order. Is it possible?. If possible, kindly let me know the configurational changes to be made so that MTO stock can used in MTS order. regards Ram Edited by: Ram-SAPSD on Sep 24, 2010 11:34
-
How to change username and password in application connection?
Hi all! when i create a application connection(10gAS), i must enter ias_admin and password, and EJB connection i must enter one user. but i don't know which user. can you tell me user and password of that user? and if i want change username and passw
-
My documents are printing in Asian font. I have HP officejet6310 all in one. When I go into properties, then advanced, "Download Asian Fonts" is checked, but I'm unable to uncheck. Any ideas?
-
Migrate datas from RDB to Oracle 10g
The applications that use the RDB database are being re-write with Forms based on an Oracle database. Of course, before we use the new application, we will have a step for moving datas from old tables in Rdb to the new tables (new design) in Oracle (
-
Help Would be cool!!
Hi, I'm trying to deploy my business components to my middle tier to access data in Oracle 8i. I have to make a JDBC connection from my middle tier to 8i(the IIOP connection to 8i just doesn't work) Can I do this by simple creating a .jar for the bus