簡體   English   中英

為什么在 main 方法中聲明實例變量?

[英]Why Are the Instance Variables Declared in the Main Method?

我正在 Codecademy 上學習 Java,最近完成了一個計算汽車貸款每月還款額的項目。 問題是我不理解解決方案,並且沒有人在 Codecademy 論壇上回答我的問題。

為什么在主方法 scope 中創建實例變量,而不是在聲明 class 之后? 在這個項目之前,我們沒有看到任何這樣的例子,我不明白。

這是代碼:

//Calculates monthly car payment
public class CarLoan {
//Why aren't the variables created here rather than in the main method?
  public static void main(String[] args) {

    int carLoan = 10000;
    int loanLength = 3;
    int interestRate = 5;
    int downPayment = 2000;

    if (loanLength <=0 || interestRate <=0) {
      System.out.println("Error! You must take out a valid car loan.");
  } else if (downPayment >= carLoan) {
      System.out.println("The car can be paid in full.");
  } else {
      int remainingBalance = carLoan - downPayment;
      int months = loanLength * 12;
      int monthlyBalance = remainingBalance / months;
      int interest = (monthlyBalance * interestRate) / 100;
      int monthlyPayment = monthlyBalance + interest;
      System.out.println(monthlyPayment);
    }
  }
}

在方法中定義的變量是局部變量,它們屬於方法的調用,而不是 object 的實例。

目的似乎是提供一個示例,讓尚未了解構造函數、實例變量和方法的初學者可以理解。 他們想教授局部變量聲明、一些簡單的計算和 if 語句,以及在進入其他內容之前打印到控制台。

作為練習,您可以更改 CarLoan class 以為其提供實例變量,只是為了看看另一種方法。 保持變量值硬編碼,創建一個計算每月付款的實例方法,並讓 main 方法將結果打印到控制台。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM