Java 从一个方法到另一个方法访问double
我是java的初学者,只需要知道如何在一个方法和另一个方法之间使用这个变量,因为它是赋值的一部分。请帮忙Java 从一个方法到另一个方法访问double,java,intellij-idea,Java,Intellij Idea,我是java的初学者,只需要知道如何在一个方法和另一个方法之间使用这个变量,因为它是赋值的一部分。请帮忙 public class parking { public static void input(String args[]) { int hoursParked = IO.getInt("(\\(\\ \n(-,-) How many hours were you parked?\no_(\")(\")"); double bill = hoursParked
public class parking {
public static void input(String args[]) {
int hoursParked = IO.getInt("(\\(\\ \n(-,-) How many hours were you parked?\no_(\")(\")");
double bill = hoursParked * 0.5 + 2;
}
public static void output(String args[]) {
System.out.println(" Parking");
System.out.println("$2 Fee plus $0.50 every hour!");
System.out.println("\nYour amount owed is $" + bill + "0");
}
}在您的代码中,
bill
是input
中的局部变量。您不能从外部输入引用该变量
如果input
和output
是独立的方法,那么通常的做法是将它们作为实例方法,并创建一个parking
实例来使用这些方法。它允许您将bill
存储为实例变量(也称为“实例字段”)。(通常情况下,课程最初是有上限的,例如,停车
,因此我将在这里这样做。)
(Java使得在引用实例成员时使用这个。
是可选的。我一直主张使用它,如上所述,以明确我们没有使用局部变量。其他观点各不相同,认为它不必要且冗长。这是一个风格问题。)
用法
或者,从input
返回bill
的值,然后将其传递到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
执行任何操作,因此我在上面删除了它。您可以声明为类变量,然后访问它
public class parking {
private double bill;
public void input(String args[]) {
int hoursParked = IO.getInt("(\\(\\ \n(-,-) How many hours were you parked?\no_(\")(\")");
bill = hoursParked * 0.5 + 2;
}
public void output(String args[]) {
System.out.println(" Parking");
System.out.println("$2 Fee plus $0.50 every hour!");
System.out.println("\nYour amount owed is $" + bill + "0");
}
我在方法输入中声明了bill,并需要将其放在一个SOUT中的输出方法中。您需要了解变量的范围。这些只是input
方法中的局部变量。它们不是类变量。如果要跨方法使用它们,则需要将它们声明为这样。谢谢您的帮助!谢谢你的解释!
double bill = parking.input(args);
parking.output(bill);
public class parking {
private double bill;
public void input(String args[]) {
int hoursParked = IO.getInt("(\\(\\ \n(-,-) How many hours were you parked?\no_(\")(\")");
bill = hoursParked * 0.5 + 2;
}
public void output(String args[]) {
System.out.println(" Parking");
System.out.println("$2 Fee plus $0.50 every hour!");
System.out.println("\nYour amount owed is $" + bill + "0");
}