从另一个字段访问一个字段的字段?

时间:2013-03-06 16:33:48

标签: java

就像说我有两个课程Class1Class2,我想在if中使用字段制作Class2语句(例如int option来自Class1

我尝试创建一个对象:

Class1 object = new Class1();

Class2中,然后编写if语句:

if(object.option == 2)

但它不起作用。

import java.util.Scanner;

public class Class1 {
    public static void main(String[] args) {
        Class2 obj = new Class2();
        int option;
        Scanner input = new Scanner(System.in);
        System.out.print("Enter an option of 1, 2 or 3");
        option = input.nextInt();
        obj.input();
    }
}

public class Class2 {

    public void input(){
        Class1 object = new Class1();
        if(object.option == 1){
            System.out.print("You've selected the option 1");
        }
        else if(object.option == 2){

            System.out.print("You've selected the option 2");
        }
        else if (object.option == 3){
            System.out.println("You've selected the option 3");
        }
    }
}

我收到编译错误:选项无法解析为字段

4 个答案:

答案 0 :(得分:1)

您在option的{​​{1}}方法中声明了main(),这意味着它不会存在于该方法之外。您需要在类中但在任何方法之外声明它。此外,由于您是从另一个类访问它,它需要是Class1(实际上没有必要,因为我现在看到两个类都在同一个包中)(但请参阅lpaloub的答案)。对于此特定主题,请阅读http://docs.oracle.com/javase/tutorial/java/javaOO/variables.htmlhttp://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

但是,您的代码仍然无法按照您的意图运行。当你遇到这些问题时,我们可能会遇到你。在此期间,您应该学习http://docs.oracle.com/javase/tutorial/java/index.html

答案 1 :(得分:0)

在Class1中你必须声明你的int是公开的,但这不是最好的方法。

最好的方法是在Class1中创建一个返回int:

的get类

public int get(){ return (your int); } 然后在Class2中,您将其称为object.get()

希望这有帮助

答案 2 :(得分:0)

确保option中的Class1字段具有正确的访问修饰符。例如,如果它是私有的,您将无法在课外使用它。将字段设置为public应该可以完成工作。可悲的是,没有任何其他细节,我无法给出更具体的答案。

答案 3 :(得分:0)

您可以在Class2中使用比较值

的方法
 public class Class2 {
     int willBeCompared = 2;

     public boolean compareToAnotherNumber(int option) {
        return option == willBeCompared;
     }
 }

它会像这样使用:

 Class1 object = new Class1();
 Class2 comparer = new Class2();

 system.out.println(comparer.compareToAnotherNumber(object.option));