在你的代码,bill
是input
一个局部变量。您不能从input
以外引用该变量。
如果input
和output
是要分开的方法,那么平常的事情将是使他们实例方法,并创建一个parking
实例使用的方法。这允许您将bill
作为实例变量(又名“实例字段”)存储。 (正常班最初封顶,如Parking
,所以我会在这里这样做。)
public class Parking {
private double bill;
public Parking() {
this.bill = 0.0;
}
public void input() {
int hoursParked = IO.getInt("(\\(\\ \n(-,-) How many hours were you parked?\no_(\")(\")");
this.bill = hoursParked * 0.5 + 2; // Or perhaps `+=`
}
public void output() {
System.out.println(" Parking");
System.out.println("$2 Fee plus $0.50 every hour!");
System.out.println("\nYour amount owed is $" + this.bill + "0");
}
}
(Java使得参照实例成员时,可选择使用this.
。我一直主张用它,因为上面,使明确我们没有使用一个局部变量,其他众说纷纭,说这是不必要的,繁琐。这是一个风格问题。)
使用
Parking p = new Parking();
p.input(args);
p.output();
或者,回报的bill
从input
然后将值将它传递到output
:
public class Parking {
public static double input() {
int hoursParked = IO.getInt("(\\(\\ \n(-,-) How many hours were you parked?\no_(\")(\")");
return hoursParked * 0.5 + 2;
}
public static void output(double bill) {
System.out.println(" Parking");
System.out.println("$2 Fee plus $0.50 every hour!");
System.out.println("\nYour amount owed is $" + bill + "0");
}
}
用法:
double bill = parking.input(args);
parking.output(bill);
边注:由于既不input
也不output
就与args
什么,我已经删除它以上。
我在方法输入中声明了bill,并且需要将它放在SOUT中的输出方法中。 –
您需要了解变量的范围。 https://www.cs.umd.edu/~clin/MoreJava/Objects/local.html – kosa
这些只是你的'input'方法中的局部变量。他们不是类变量。如果您想跨方法使用它们,则需要声明它们。 –