繁体   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