我是Java环境的新手,需要一些帮助,将变量从gatheringInfo
传递到printVariable
方法。 myVar
变量未通过printVariable
方法传递。
public class variableTest {
private float myVar;
public void setMyVar(float num) {
myVar = num;
}
public variableTest() {
this.myVar = 0;
}
public variableTest(float myVar) {
this.myVar = myVar;
}
public void gatheringInfo() {
Scanner scnr = new Scanner(System.in);
System.out.println("Enter Value: ");
while (!scnr.hasNextFloat()) {
System.out.println("Needs To Be An Float Type!");
scnr.next();
}
float myVar;
this.myVar = scnr.nextFloat();
}
public void printVariable() {
System.out.println("Value: " + myVar);
}
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Would You like to add a value?");
String response = scnr.next();
if (response.toLowerCase().equals("y")) {
variableTest vt = new variableTest();
vt.gatheringInfo();
} else {
System.out.println("You do not wish to add a value?");
}
variableTest vt = new variableTest();
vt.printVariable();
}
}
答案 0 :(得分:0)
发表评论后,我再次查看了您的代码,并认为我看到了您的问题。
您正在创建variableTest类的一个实例并对其进行操作,但是随后您正在创建新的variableTest实例,并在该实例上调用printVariable。我很确定您希望在“ if”块(上方)之外仅调用一次“ new variableTest()”,以便在整个代码中使用相同的“ vt”对象。
即:
public static void main(String [] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Would You like to add a value?");
String response = scnr.next();
variableTest vt = new variableTest();
if (response.toLowerCase().equals("y")) {
vt.gatheringInfo();
} else {
System.out.println("You do not wish to add a value?");
}
vt.printVariable();
}