使用来自第二类的另一个函数中的第一个类的函数的变量的值 [英] use the value of variables from a function from the first class in an another function from the second class
问题描述
我有两个类,我想使用来自第二个类的另一个函数中的第一个类的函数的variables / String的值,例如:
在这种情况下,我想使用值的字符串英语和字符串frensh从FisrtFunction包含在FirstClass中,在SecondFunction中包含在SecondClass中,请帮助修复该代码,因为它没有读取这些值
I have two classes , I want to use the value of variables/String from a function from the first class in an another function from the second class , for example : In this case I want to use the value of String english and String frensh from FisrtFunction include in FirstClass , in the SecondFunction include in SecondClass , please help to fix that code because it's didn't read those values
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++;
}
}
}
}
}
推荐答案
不可能访问在该方法之外的方法中创建的对象的值。对象仅存在于该方法中。即使在同一个类( FirstClass
)中, FirstFunction()
之外的任何方法都不能简单地使用Strings french
和 english
。
It's impossible to access the values of objects created in a method outside of that method. The objects only exist in that method. Even within the same class (FirstClass
), any method outside of FirstFunction()
cannot simply use the value of Strings french
and english
.
访问方法外的变量,使它们 public
或 protected
类实例变量,如:
If you want to be able to access the variables outside of the method, make them public
or protected
class instance variables, as in:
public class FirstClass {
public String french;
public String english;
public void FirstFunction() {
....
值将为null,除非在调用 SecondFunction()之前调用
FirstFunction()
However, their values will be null unless you call FirstFunction()
before calling SecondFunction()
这篇关于使用来自第二类的另一个函数中的第一个类的函数的变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!