【问题标题】:How to get the user input from one class to another如何将用户输入从一个类获取到另一个类
【发布时间】:2015-01-26 23:57:59
【问题描述】:

我有以下代码:

    public static void main (String args[])
    {
       Scanner reader = new Scanner(System.in); 
       System.out.println("Enter a Numerator");
       int num =reader.nextInt();
       System.out.println("Enter a Denominator");
       int den =reader.nextInt();

       System.out.println("Enter a Numerator and a Denominator");
       Rational r = new Rational(num,den); 
       System.out.println(r.getRational() + " equals " +r.getDecimal());


    }
}

class Rational
{


    double getNum()
    {
        return num;
    }


    double getDen()
    {
        return den;
    }

    //getDecimal
    double getDecimal()
    {
        double r =  num/den; 
        return r;
    }


    String getRational()
    {
      return getNum()+"/"+getDen();
    }



      private int getGCF(int n1, int n2)
      {
          int rem = 0;
          int gcf = 0;
          do
          {
              rem = n1 % n2;
              if (rem == 0)
                gcf = n2;
              else
              {
                  n1 = n2;
                  n2 = rem;
              }
          }
          while (rem != 0);
          return gcf;
      }
}

代码的目的是让用户输入分子和分母。然后程序将除法并给出方程的答案。我需要帮助的是,我在代码阅读行中不断收到错误:Rational r = new Rational(num,den)。我不知道为什么。

【问题讨论】:

  • 错误说明了什么?
  • 看起来您需要 Rational 类中的构造函数,该构造函数接收 num、den 并调用该类中的 set set 函数。
  • 你必须在Constructors, and access modifiers in JAVA阅读更多内容
  • 错误表示类 Rational 中的构造函数 Rational 不能应用于给定类型。

标签: java input


【解决方案1】:

您忘记在Rational-Class 中设置构造函数。您尝试使用以下方式启动对象:

Rational r = new Rational(num,den); 

但只有标准的构造函数Rational()。要实现这一点,您可以调用此构造函数,您必须添加此构造函数:

private int num =0;
private int den =0;
public Rational(int unum, int uden){
  this.num = unum;
  this.den = uden;
}

在您的Rational-Class 中,您必须使用this.numthis.den来获取构造函数设置的对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-21
    • 1970-01-01
    • 2016-10-30
    • 2017-03-25
    • 1970-01-01
    • 2016-05-19
    相关资源
    最近更新 更多