gpt4 book ai didi

java - 从一种方法到另一种方法访问 double 值

转载 作者:行者123 更新时间:2023-11-30 02:48:21 25 4
gpt4 key购买 nike

我是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 * 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");

}

}

最佳答案

在您的代码中,billinput 中的局部变量。您无法从外部输入引用该变量。

如果inputoutput是单独的方法,那么通常的做法是将它们设为实例方法并创建一个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();

或者,从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);
<小时/>

旁注:由于 inputoutput 都没有对 args 执行任何操作,因此我已将其删除。

关于java - 从一种方法到另一种方法访问 double 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39473290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com