为什么要在main方法中声明实例变量?

Why Are the Instance Variables Declared in the Main Method?

我正在 Codecademy 上学习 Java,最近完成了一个计算汽车贷款每月还款额的项目。问题是我没看懂解决办法,Codecademy论坛上也没有人回复我的问题

为什么实例变量是在 main 方法范围内创建的,而不是在 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);
    }
  }
}

方法中定义的变量是局部变量,属于方法的调用,不属于对象的实例。

其目的似乎是提供一个示例,让没有接触过构造函数、实例变量和方法的初学者可以理解。他们想教授局部变量声明、一些简单的计算和 if 语句,以及在进入其他内容之前打印到控制台。

作为练习,您可以更改 CarLoan class 以为其提供实例变量,只是为了了解另一种方法。保持变量值硬编码,制作一个计算每月付款的实例方法,并让主要方法将结果打印到控制台。