2016-09-13 183 views
0

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

} 

}

+0

我在方法输入中声明了bill,并且需要将它放在SOUT中的输出方法中。 –

+0

您需要了解变量的范围。 https://www.cs.umd.edu/~clin/MoreJava/Objects/local.html – kosa

+0

这些只是你的'input'方法中的局部变量。他们不是类变量。如果您想跨方法使用它们,则需要声明它们。 –

回答

1

在你的代码,billinput一个局部变量。您不能从input以外引用该变量。

如果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(); 

或者,回报billinput然后将值将它传递到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什么,我已经删除它以上。

+0

感谢您的解释! –

0

您可以声明为类变量,然后访问它。

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"); 
} 
+0

感谢您的帮助! –

相关问题