【问题标题】:constructor Rational in class Rational cannot be applied to the given types?类 Rational 中的构造函数 Rational 不能应用于给定类型?
【发布时间】:2013-01-19 02:04:40
【问题描述】:

所以这个程序的要点是创建一个 Rational 类,这样当您运行它时,会出现一个 GUI 输入并要求输入分子和分母。然后它将返回减少的分数。但我不断收到此错误消息,我不知道为什么。到目前为止的程序如下:

import javax.swing.JOptionPane;


public class lab8
{
public static void main (String args[])
{
    String strNbr1 = JOptionPane.showInputDialog("Enter Numerator ");
    String strNbr2 = JOptionPane.showInputDialog("Enter Denominator ");

    int num = Integer.parseInt(strNbr1);
    int den = Integer.parseInt(strNbr2);

    Rational r = new Rational(num,den);
    JOptionPane.showMessageDialog(null,r.getNum()+"/"+r.getDen()+" equals "+r.getDecimal());

    System.exit(0);
}
}



class Rational
{
private int num;
private int den;

public Rational()
{
    num = 0;
    den = 1;
}
public double getNum()
{
    return num;
}

public int getDen()
{
    return den;
}
 }

【问题讨论】:

  • 确切的错误信息是什么?它指的是哪一行代码?
  • 它是“Rational 类中的构造函数 Rational 不能应用于给定类型;”
  • 错误信息将引用特定的代码行;是哪个?
  • 指的是 Rational 类
  • Rational r = new Rational(num,den);

标签: java constructor rational-number fractions


【解决方案1】:

您正在尝试调用一个不存在的构造函数。 你的类构造函数什么都不要求:

public Rational()

虽然它应该要求 2 个整数:

public Rational(int num, int den){
     this.num = num;
     this.den = den;
}

这样您就可以将numden 都传递给它,就像您尝试做的那样

Rational r = new Rational(num,den);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    • 2020-06-21
    • 1970-01-01
    相关资源
    最近更新 更多