2014-02-27 88 views
-2

下面的代码应该让用户输入建筑物的平方英尺和故事。我一直在主要和我的生活中的代码存在问题,我无法弄清楚为什么。java:非静态变量不能从静态上下文中引用错误

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); 

感谢您的帮助

+5

将你的头转向显示器的右侧,看看'Related'部分。 –

+1

在右侧的“相关”下查看。从静态上下文中引用的非静态事物有多少个问题?其中之一肯定会对你有一个很好的答案。 –

+0

当你在第48行使用'area'时,你期望它来自哪里? –

回答

0

问题是与areafloors。你在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; 
    } 

    pubic 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); 
+0

我应该改为什么?我必须使用一些论据。 – NJD

+0

我需要用户输入变量数据。 – NJD

+0

对于12k,你应该知道这个问题是重复的,但你确实回答了,因此-1。 (答案也不是很有启发性。) – Ingo

相关问题