java - 如何在Java中的另一个类中使用一个类中的变量

标签 java class intellij-idea methods

我对java很陌生。我正在编写这个程序来计算复利和单利以及我将来会添加的一些其他内容。

语法-

类数据

import java.util.Scanner;
public class DATA {
    public static void main(String[] args) {
        Scanner m=new Scanner(System.in);
        System.out.println("What do you want to calculate SI/CI");
        String choice=m.nextLine();
        {
            if (choice.equalsIgnoreCase("si") || choice.equalsIgnoreCase("ci"))
                Interest.var();
            if (choice.equalsIgnoreCase("si")){
                Interest.ci();
            }
        }


    }
}

类(class)兴趣

import java.util.Scanner;

public class Interest {
    public static void var(){
        Scanner m=new Scanner(System.in);
        System.out.println("Enter the principle");
        double p=m.nextDouble();
        System.out.println("Enter the rate");
        double r=m.nextDouble();
        System.out.println("Enter the time");
        double t=m.nextDouble();
    }
     public static void si(double p, double r, double t){
        double si=(p*r*t)/100;
        System.out.println("The Simple Interest is "+si);
    }
    public static void ci(double p, double r, double t){
        double ci=p*Math.pow((1+(r/100)),(t))-p;
        System.out.println("The Compound Interest is "+ci);
    }
}

我在 Interest 类中创建了一个名为 var 的方法,它需要原理和其他数据来进行计算。因此,如果用户要求计算 CI/SI,它会导入 var 方法并提出问题。现在我无法找出使用这些变量进行计算的方法。 我希望你们能帮助我,欢迎批评和建议,但如果你们能帮助我解决当前的问题,那就更有帮助了,而且我对java真的很陌生

最佳答案

在类 Interest 中创建私有(private)变量 p、r 和 t。创建一个构造函数并传递 3 个值。因此,如果调用方法 si() 或 ci(),则可以简单地使用 this.p、this.r 和 this.t 来计算。您还可以删除 si() 和 ci() 方法中的参数。

关于java - 如何在Java中的另一个类中使用一个类中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61588683/

相关文章:

java - 将 UUID 值插入 PostgreSQL 数据库时出现 Liquibase 问题

java - 用Java实现二叉搜索树

java - 从 jTextField 到表 sql 的查询插入错误

javascript - 在 javascript 中定义属性方法的正确模式 "class"

c++ - 交替使用类作为浮点指针

java - 重命名 Intellij 中多个子类中使用的变量

java - 如何使 jPanel 可滚动

java - 在 Java 中,将变量直接分配给包装类是一个好的做法吗?

IntelliJ IDEA 中的 Scala 控制台要么接受输入,要么打印输出,命令从 temrinal 运行

java - 在 IntelliJ 中将 "new"设置为后缀完成