-5

就像说我有两个类,Class1Class2,并且我想在使用来自的字段(例如:)if时发表声明。Class2int optionClass1

我尝试创建一个对象:

Class1 object = new Class1();

in 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

4 回答 4

1

您在 for 方法中声明optionmain()Class1意味着它不会存在于该方法之外。您需要在类中但在任何方法之外声明它。此外,由于您是从另一个类访问它,所以它需要public(实际上没有必要,因为我现在看到两个类都在同一个包中)(但请参阅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

于 2013-03-06T16:54:40.250 回答
0

在 Class1 中,您必须将您的 int 声明为 public,但这不是最好的方法。

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

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

希望这可以帮助

于 2013-03-06T16:37:43.637 回答
0

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

于 2013-03-06T16:37:45.510 回答
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));
于 2013-03-06T16:37:47.547 回答