2016-09-13 232 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

感謝您的幫助! –

相關問題