繁体   English   中英

将值传递给Java中的分数类

[英]Passing the values to the fraction class in java

如果我要编写一个新程序并想拥有一个分数类,而我的书称之为驱动程序类,那是一个主类,而我有这样的代码

// Driver class

import java.util.Scanner;

public class DriverClass{

    public static void main(String[] args){

        Scanner stdIn = new Scanner(System.in);
        Fraction c, d;

        System.out.println(" Enter a numerator then a denominator:");
        c = new Fraction( stdIn.nextInt(), stdIn.nextInt());
        c.print();

       System.out.println(" Enter a numerator then a denominator:");
        d = new Fraction( stdIn.nextInt(), stdIn.nextInt());
        d.print();
    }
}
...

在我的分数班级中,我有一种称为公共分数的方法。 如何设置来自扫描仪util的驱动程序类中来自分数c的两个数字,这又将如何将c值替换为来自分数d的值? 我正在上一门Java课,这是我不了解的家庭作业的一部分。 我试图将这些值传递给分数类,因为最后我必须将这两个分数相加并相乘。

// begining of class

public class Fraction{

    private int numerator;
    private int denominator;

    // well this is what my problem is, how do I call for c 
    // twice in the Fraction class
    public int Fraction(int num, int denom){

this.numerator = num;

this.denominator = denom;
}
    // is this the right way to recieve the fraction 
    // from the driver class for both c and d?

}

有人可以帮我吗

您的Fraction方法是一种定义为返回int的方法,但是您正在调用它就好像它是构造函数一样。

构造函数不返回任何内容,因此请勿声明任何返回类型。 (它们甚至没有void类型,因此编译器知道它们是构造函数,而不是方法,需要用new调用。这是一个小错误,Java允许您声明与类同名的方法,IIRC是其中的一种。 Java Puzzlers中的难题可以做到这一点)。

从定义中删除“ int ”返回类型:

public class Fraction{

    private int numerator;
    private int denominator;

    public  Fraction(int num, int denom) {
        //...

如何设置来自扫描仪util的驱动程序类中来自分数c的两个数字,这又将如何将c值替换为来自分数d的值?

您要对new Fraction(..,..)进行两次调用。 每次使用new ,它都会创建所请求类的新对象,然后使用您提供的值调用该对象上的构造函数。 因此cd将保存对Fraction不同实例的引用。 由于Fractionnumeratordenominator字段未标记为static ,因此Fraction每个实例将具有这些字段的自己的副本,因此传递给对象构造函数的值将存储在变量c中,该对象的引用将存储在变量c中。第一个新对象,第二个新对象中的d 由于它们是不同的对象,因此这些值不会相互替换。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM