使用来自第二个类中另一个函数中第一个类的函数的变量值

时间:2014-01-10 18:52:26

标签: java function class variables

我有两个类,我想使用来自第二个类中另一个函数中第一个类的函数的variables / String的值,例如: 在这种情况下我想使用String english的值和来自FisrtFunction的String frensh包含在FirstClass中,在SecondClass中包含SecondClass,请帮助修复那段代码,因为它没有读取那些值

public class FirstClass {
  public void FirstFunction() {
    String french;
    String english;
    try(BufferedReader br = new BufferedReader(new FileReader("text.txt"))) {
      String line;        
      while ((line = br.readLine())!=null) {
               String[] pair = line.split(";");
               french=(pair[0]);
               english=(pair[1]);  
      }
    }
  }
}

public class SecondClass {
  public void SecondFunction extends FirstClass () {
    int i=0;   
    boolean bool=true;    
    String reponce;
    InputStreamReader isr = new InputStreamReader(System.in); 
    BufferedReader in = new BufferedReader(isr); 

    while (i<nbquest && bool) {
      System.out.println("donner la traduction de "+french);
      String reponseee  = in.readLine();     
      traduction = reponseee;  

      if(bool == true ) { 
        if(traduction.equals(english)) {
          score++;
          abc++;
          System.out.println("Bravo! Bonne reponse");
        } else {
          System.out.println("Mauvaise reponse");
          abc++;
        }
      }
    }
  }
}

2 个答案:

答案 0 :(得分:0)

我建议在尝试编写这样的代码之前先阅读一下Java的基础知识......然而,定义你的第一个类是这样的:

public class FirstClass {
    protected String french;
    protected String english;

    public void FirstFunction() {
        try {
            BufferedReader br = new BufferedReader(new FileReader("text.txt"));
...
}

这将使继承的类可以使用类成员,而不是方法的局部变量,使它们对外部类不可见。

我确信在你解决这个问题之后你会有更多的问题要问,因为你的代码还有很多问题。

答案 1 :(得分:0)

无法访问在该方法之外的方法中创建的对象的值。对象仅存在于该方法中。即使在同一个班级(FirstClass)内,FirstFunction()之外的任何方法都不能简单地使用字符串frenchenglish的值。

如果您希望能够访问方法之外的变量,请将它们设为publicprotected类实例变量,如:

public class FirstClass {
  public String french;
  public String english;
  public void FirstFunction() {
    ....

但是,除非您在致电FirstFunction()

之前致电SecondFunction(),否则他们的值将为空