So i'm having a bit of a problem trying to compare two strings declared in the Main class. I've messed around with it and i really can't get it to work! The problem is in the if() statement where i compare the variables...
public class Main {
public String oldContent = "";
public String newContent = "";
public static void main(String[] args) throws InterruptedException {
Main downloadPage = new Main();
downloadPage.downloadPage();
oldContent = newContent;
for (;;) {
downloadPage.downloadPage();
if (!oldContent.equals(newContent)) { // Problem
System.out.println("updated!");
break;
}
Thread.currentThread().sleep(3000);
}
}
private void downloadPage() {
// Code to download a page and put the content in newContent.
}
}
the variables are instance members, whereas the for happens in a static method.
try moving the actual function to an instance method (not static), or conversely make the data members static as well.
You may use name of the object you have created (downloadPage ) to access to the parameters:
in the main finction use following instead of parameter names only:
downloadPage.oldContent
downloadPage.newContent
The variables are inside the Main object:
public static void main(String[] args) throws InterruptedException {
Main downloadPage = new Main();
downloadPage.downloadPage(); // Access them like you accessed the method
downloadPage.oldContent = downloadPage.newContent;
for (;;) {
downloadPage.downloadPage();
if (!downloadPage.oldContent.equals(downloadPage.newContent)) {
System.out.println("updated!");
break;
}
Thread.currentThread().sleep(3000);
}
}
Do consider using getters and setters instead of exposing the fields.
See non static/ static variable error
Related
I have a static nested class StatClass, the file name is Example.java
class OuterClass
{
public static class StatClass
{
System.out.println("Hello"); // This line doesn't work
void pow()
{ System.out.println("Hello W");}
}
}
public class Example
{
public static void main(String[] args)
{
OuterClass.StatClass statInner1 = new OuterClass.StatClass();
statInner1.pow();
}
}
The first println statement doesn't work in the static nested class i.e if its removed then the program compiles, although the println statement works when inside the pow() method, couldn't understand this
Like in a normal class, you can't just put statements inside a class. You could put it in an initializer-block like this:
{
System.out.println("Hello");
}
Or in a constructor, or a method. Whatever you want.
I am just uniting the two answers so far:
one option is a static block
class OuterClass
{
public static class StatClass
{
static {
System.out.println("Hello"); // This line doesn't work
}
void pow()
{ System.out.println("Hello W");}
}
}
public class Example
{
public static void main(String[] args)
{
OuterClass.StatClass statInner1 = new OuterClass.StatClass();
statInner1.pow();
OuterClass.StatClass statInner2 = new OuterClass.StatClass();
statInner2.pow();
}
}
The main difference is how the block is executed by the JVM. In the first case it is executed once during the class initialization. Then the output will be :
Hello
Hello W
Hello W
Another option is initializer block in which case the code will be executed on each instantiation of the class.
class OuterClass
{
public static class StatClass
{
{
System.out.println("Hello"); // This line doesn't work
}
void pow()
{ System.out.println("Hello W");}
}
}
public class Example
{
public static void main(String[] args)
{
OuterClass.StatClass statInner1 = new OuterClass.StatClass();
statInner1.pow();
OuterClass.StatClass statInner2 = new OuterClass.StatClass();
statInner2.pow();
}
}
Then the output will be:
Hello Hello W Hello Hello W
Following statement is outside method that wont work
System.out.println("Hello"); // This line doesn't work
You have to wrap these statements inside static block as follows
static{
System.out.println("Hello"); // This line will work
}
this block will execute when JVM create static instances.
System.out.println("Hello");
This does not work because,the control never goes to the line. Unless you define this inside a function and use the object you created to call it OR use the static block which does not require an object to call it OR an initializer block, it will not work. I hope that helps
My Code:
(causes a Stack Overflow Error)
public class Overloads {
String uniqueID;
Overloads ov2=new Overloads();
public static void main(String[] args) {
System.out.println("IN MAIN");
}
public void setUniqueID(String theID) {
// II lots of validation code, and then:
uniqueID = theID;
System.out.println(uniqueID);
}
}
This Code Works Fine:
public class Overloads {
String uniqueID;
public static void main(String[] args) {
Overloads ov2=new Overloads();
System.out.println("IN MAIN");
}
public void setUniqueID(String theID) {
// II lots of validation code, and then:
uniqueID = theID;
System.out.println(uniqueID);
}
}
The presence of main method is not relevant here. The scope in which you have declared the variables, however, is very important.
Have you walked through what happens in the first version of the code?
Create new instance of Overloads
-> ov2 = Create new instance of Overloads
-> ov2 = Create new instance of Overloads
-> ov2 = Create new instance of Overloads
and so on. The variable ov2 is in scope of the class, thus it is initialized whenever an instance of the class is instantiated. This will never terminate until you run out of memory and get the stack overflow. Run it with a debugger for a clearer view.
The second version of the code only instantiates one instace of Overloads, in the scope of the main method. Thus creating one instance does not lead to the newly created instance creating new instance and so on..
You can do like this
public class Overloads {
String uniqueID;
static Overloads ov2 = new Overloads();
public static void main(String[] args) {
System.out.println("IN MAIN");
}
public void setUniqueID(String theID) {
// II lots of validation code, and then:
uniqueID = theID;
System.out.println(uniqueID);
}
}
this will create shared instance of Overloads, instantiation will be done only once, when class loaded
This question already has answers here:
Java: How To Call Non Static Method From Main Method?
(9 answers)
Closed 9 years ago.
hello i whave an function which it take the number after the (.) and after "Vl" in string
so i want call this function on the code but they tell me this error
non-static method Ajuster(String) cannot be referenced from a static context
this the code
public class Test {
public Integer Ajuster(String data) {
Integer vlan=0;
if (data.indexOf("Vl") >= 0) {
int pos = data.indexOf("Vl") + 2;
String vl = data.substring(pos, data.length());
vlan=Integer.parseInt(vl.trim());
} else {
int pos = data.lastIndexOf(".") + 1;
String vl = data.substring(pos, data.length());
try {
vlan=Integer.parseInt(vl.trim());
} catch (Exception e) {
e.printStackTrace();
}
}
return vlan;
}
public static void main(String[] args) {
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/mohammedia", "root", "123456");
String sql = "SELECT * FROM router;";
Telnet_Interface telnet = new Telnet_Interface();
Telnet_Ressources telnet_R = new Telnet_Ressources();
Telnet_Interface telnet1 = new Telnet_Interface();
Telnet_Interface telnet2 = new Telnet_Interface();
PreparedStatement prest = conn.prepareStatement(sql);
ResultSet res=prest.executeQuery();
while(res.next()){
telnet1.Config(res.getString(1), "noc", "nocwana", res.getString(1));
telnet2.Config(res.getString(2), "noc", "nocwana", res.getString(2));
}
ArrayList myData=telnet.getMyData();
ArrayList myData1=telnet1.getMyData();
ArrayList myData2=telnet2.getMyData();
for(int i=0;i<myData1.size();i++)
{
String data1=myData1.get(i).toString();
Integer vl1=Ajuster(data1);
System.out.print(vl1);
}
}
}
so the problem it's about the line: Integer vl1=Ajuster(data1);
Thank you
main is static. It means that it is not related to a instance of the Test class, but to the class itself.
Ajuster (please follow Java coding guidelines, it should be ajuster) is not static, so it is related to an instance of Test. So, to use it you must use it from a created instance (like this)
Test test = new Test();
test.ajuster();
or make it static (try not to overuse static methods)
It seems you're calling the method public Integer Ajuster(String data) that is non-static from the main that's, in fact, static. In order to call that method Ajuster you must instantiate an object of the class Test.
I suppose you know how to do this, but however you must write this down Test test = new Test().
You cant call a non-staic without any object reference.
Either make the method static like (depends if it dont involve any instance varialbe)
public static Integer Ajuster(String data)
or invoke with a object of class Test like
Test obj = new Test();
obj.Ajuster("data");
or better this http://docs.oracle.com/javase/tutorial/
PS: Method starting with capital name looks really weird
You cannot call a non-static method with out creating an object. If it's a non-static context, however current object (this) will be there. If from static method you have to create an object and call the method on that object.
Static methods are all same for every object. In that case, we cannot know on what object are we applying the method or accessing a variable, that's why there is restriction.
Alternatively, you can make the method as static. But that depends. You should know when to use static methods and when not to use. It's a design issue.
Read:
To know the difference between static and non-static method
When should a method be static
How to call a non static method from main
So, create an object and call the method:
Test newTest = new Test();
newTest.ajuster();
You have to understand that non-static context cannot be referred in static context
public int test = 0;
public static void main(String[] args) {
test += 4; //this wont compile
}
Non-static context however can include both non-static and static contexts.
Try something like this.
public class Test {
public int test = 0;
public static void main(String[] args) {
new Test();
}
public Test() {
test += 4; //this will compile
}
}
If you cannot understand this, try to search and learn about Constructor
public class test {
public static void main(String[] args) throws Exception {
final int num = 111;
new Thread() {
#Override
public void run() {
num = 222;
}
}.start();
}
}
I want to change the value of num however I can only do that if I set it to final which would not let me modify this. In other languages such as C we can use pointers but Java cannot?
Java has neither closure nor pointers.
A solution would be to make the num static in the class :
public class test {
static int num = 111;
public static void main(String[] args) throws Exception {
new Thread() {
#Override
public void run() {
num = 222;
}
}.start();
}
}
Another solution would be to use an object like AtomicInteger. You can't change the value of the variable but you can change the content of the value :
public class test {
public static void main(String[] args) throws Exception {
final AtomicInteger num = new AtomicInteger(111);
new Thread() {
#Override
public void run() {
num.set(222);
}
}.start();
}
}
Why this isn't allowed
main is a method. As with other programming languages, when a method returns, all of the variables declared in its body go out of scope, and accessing them has undefined behavior. Under some circumstances, the memory location where they used to be will no longer be valid.
Obviously this is a problem. If you try to change num after main has returned, you might overwrite a portion of the stack that doesn't belong to num anymore. Java's response to this difficult situation is to introduce restrictions on how you can share variables: they must be final. Java can then safely locate them in such a way that reading them will produce consistent results even after the function has returned.
The C equivalent to this problem is storing and using the address of a local variable outside of its scope, something that all C programmers are taught to never do.
To get around it, declare num as a member of test, create an instance, and pass that to it. This removes the dependancy on a local variable, and thus removes the final restriction.
public class test
{
int num = 111;
public static void main(String[] args) throws Exception
{
test t = new test();
(new Thread(t) {
test mytest;
Thread(test t)
{
mytest = t;
}
#Override
public void run() {
mytest.num = 222;
}
}).start();
}
}
Well, you can access it if you declare variable outside the function. Like this:
public class test {
private static int num = 111;
public static void main(String[] args) throws Exception {
new Thread() {
#Override
public void run() {
num = 222;
}
}.start();
}
}
You are creating new Thread() { class as inner class. You can't access outer class variables without declaring them as final.
You can't change final variable references.
There are two ways you can do this,
1) Make num as static
2) Wrap num inside an object (You can update state of the object even though you define reference as final).
NOTE: Both are not thread safe.
Yep you can't win here! You need to set it final to be able to access it, but then you will not be able to modify it. You'll need to look at a different approach.
public class DialogBox {
public static void main (String arg[]) {
String inputCourseCode;
inputCourseCode = this.inputCourseCode();
}
public String inputCourseCode() {
String input = JOptionPane.showInputDialog("Input the course code of this course:");
return input;
}
}
How to call the method inputCourseCode in main function?
You need to have an instance of DialogBox in order to call the inputCourseCode method.
For example:
public static void main (String arg[])
{
String inputCourseCode;
DialogBox box = new DialogBox();
inputCourseCode = box.inputCourseCode();
}
main is a static method; consequently, it does not have access to a 'this' reference.
It's an instance method, so you need an instance of DialogBox to call the method.
public static void main (String arg[]) {
DialogBox foo = new DialogBox();
String inputCourseCode = foo.inputCourseCode();
}
It needs to be static
public static String inputCourseCode()
then within Main you remove the this.
public static void main (String arg[]) {
String inputCourseCode;
DialogBox d = new DialogBox(); //create instance
d.inputCourseCode(); //call method
}
inputCourseCode is a method of DialogBox class, you need a reference to an instance of that class to call it.
If you need to call that function without an istance class you need to declare it as static:
public static String inputCourseCode() {
String input = JOptionPane.showInputDialog("Input the course code of this course:");
return input;
}
Then you can call it from main without create an object:
public static void main (String arg[]) {
String inputCourseCode;
DialogBox.inputCourseCode(); //call static method
}
new DialogBox().inputCourseCode();
You need to instantiate your class to access non-static members.
See Java Tutorial: Understanding Instance and Class Members
Well it depends on your need.
If you want it to be tied at class level, then just make it static and remove 'this' from this.inputCourseCode() in the current code and it will work.
If you want it to be part of each object then you need to create object of DialogBox and call it explicitly as follows :
DialogBox dialogBox = new DialogBox();
dialogBox.inputCourseCode();