java:非静态变量无法从静态上下文错误中引用

时间:2014-02-27 22:44:52

标签: java static

以下代码应该让用户输入建筑物的平方英尺和故事。我一直在主要代码和我的生活中遇到问题,我无法弄清楚原因。

import java.util.*;

public class Building
{
static Scanner console = new Scanner(System.in);

double area, squarefootage;
int floors, stories;
char ans

void get_squarefootage()
{
System.out.println ("Please enter the square footage of the floor.");
area = console.nextDouble();
}

void set_squarefootage(double area)
{
squarefootage = area;
}

void get_stories()
{
System.out.println ("Please enter the number of floors in the building.");
floors = console.nextInt();
}

void set_stories(int floors)
{
stories = floors;
}

void get_info()
{
System.out.println (" The area is: " + squarefootage + " feet squared");
System.out.println (" The number of stroies in the building: " + stories + " levels");
}

public static void main(String[] args)
   {

   Building b = new Building();
   b.get_squarefootage();
   b.set_squarefootage(area);
   b.get_stories();
   b.set_stories(floors);
   System.out.println ("---------------");
   b.get_info();
   System.out.println ("Would you like to repeat this program? (Y/N)");

}
}

我遇到的问题是在第48和50行,它显示错误;

Building.java:48: error: non-static variable area cannot be referenced from a static context
   b.set_squarefootage(area);
                       ^
Building.java:50: error: non-static variable floors cannot be referenced from a static context
   b.set_stories(floors);

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

问题在于areafloors。您可以在static main方法中使用它们。这是不允许的。

什么是static,为什么这么重要?

在Java中,您创建的所有内容都声明了可见性范围。您可以在包中,在创建类的文件中以及在store members的文件中分配文件。

一般概念是一个类是你创建对象的模板。当您有对象时,可以将值设置为其字段并调用其方法,操作将仅反映在对象内部,并且所有值都将分配给对象。当您使用静态关键字时,您将成员标记为不再是对象的一部分,而只是所有对象共有的类的元素。

让我们看一下例子

class Sample {

  private int instance_value;
  private static int class_value;

  Sample(int first, int second) {
     instance_value = first;
     class_value   = second;
  } 

  public void print() {
     System.out.printf("instance_value=%i, class_value=%i\n",instance_value, class_value);
  }      

}

我们现在创建了两个类Sample的对象。

 Sample objectOne = new Sample(1,2);
 objectOne.print();

 Sample objectTwo = new Sample(3,4);
 objectOne.print();

输出将是:

instance_value=1, class_value=2
instance_value=1, class_value=4

class_value中更改为4的原因是因为它是静态的,并且对于使用它的所有元素都是相同的。

注意,您可以从非静态访问静态成员,您不能做的是从静态访问非静态成员。

不使用您在类体中声明的名称,而是在主

中设置值

你有这个

 b.set_squarefootage(area);
 b.set_stories(stories);

你可能想要这个

 b.set_squarefootage(50.0);
 b.set_stories(5);

或再次定义它们以涵盖范围。

double area = 50.0;
int    storied = 5;

 b.set_squarefootage(area);
 b.set_stories(stories);