PDA

View Full Version : سوال: پیغام خطا



ghsama
جمعه 13 فروردین 1395, 20:25 عصر
با سلام خدمت دوستان عزیز.
من تازه کار هستم .
با خطای زیر روبرو شدم.
non-static variable this cannot be referenced from a static contextاینم از کدی که در حال نوشتن اون بودم. به نظرتون مشکل کار من از کجاست؟


package firstjavaprogram;
import firstjavaprogram.Firstjavaprogram.Box;
/**
*
* @author Ghs
*/
public class Firstjavaprogram {
public class Box
{
double width;
double height;
// structors Section
Box(double width , double height)
{
this.width=width;
this.height=height;
}
Box()
{
this.width=5;
this.height=2;
}
// methods Section
public double mohiteMostatil ()
{
return width*height;
}
public double masahat ()
{
return width*4;
}


}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
در این خط خطا رخ میدهد Box myBox = new Box(5,2);
System.out.print(myBox.masahat());

}


}

[younes]
شنبه 14 فروردین 1395, 17:09 عصر
لطفا کدتون رو توی تگ جاوا قرار بدید. اصلا قابل خوندن نیست.

Ahmad_Hoghooghi
شنبه 14 فروردین 1395, 19:49 عصر
کد را به این صورت اصلاح کنید.
شما در داخل متد های Static یک کلاس (این جا main) فقط می تونید از داشته های استاتیک کلاس استفاده کنید (چون معلوم نیست کلاس instantiate شده یا نه) در واقع بهترین کار اینه که شما کلاس Box و از داخل کلاس اصلی برنامه خارج کنید، تا به راحتی یک object از اون بسازید.




//import firstjavaprogram.Firstjavaprogram.Box;
/**
*
* @author Ghs
*/
public class Firstjavaprogram {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Box myBox = new Box(5, 2);
System.out.print(myBox.masahat());

}

}

class Box {

double width;
double height;
// structors Section

Box(double width, double height) {
this.width = width;
this.height = height;
}

Box() {
this.width = 5;
this.height = 2;
}
// methods Section

public double mohiteMostatil() {
return width * height;
}

public double masahat() {
return width * 4;
}

}

hajjijo
چهارشنبه 18 فروردین 1395, 05:51 صبح
این برنامرو من اجرا کردم و کاملا درست کار میکرد فقط خط اخر یه } زیاد بود . برنامه کاملا سالمه حتی جواب هم میده بهم
20.0