如何从main方法中获取要在另一个类中使用的值?

时间:2018-01-19 17:57:51

标签: java arrays class instances

我目前正在编写一个程序来获取多项式系数和度数的用户输入,然后将这些输入转换为多项式。在我的主要方法中,我使用扫描仪获取一行字符串,然后将其转换为双数组。但是,我需要在另一个类中使用此double数组的值,但似乎无法执行此操作。我已经坚持了一段时间,甚至在研究之后我似乎仍然无法得到它。

PolynomialDemo.java

public class PolynomialDemo  {
public static int degree;
public static double[] numbers;

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter the degree of the first polynomial -> ");
    degree = scan.nextInt();

    System.out.print("Enter its coefficients in order of descending powers -> ");
    String deg = scanner.nextLine();
    String[] numbersStr = deg.split(" ");
    double[] numbers = new double[ numbersStr.length ];
    for ( int i = 0; i < numbersStr.length; i++ )
    {
        numbers[i] = Integer.parseInt( numbersStr[i] );
    }

Polynomial.java

public class Polynomial implements PolyEval  {

private double[] coeffs;
private int degree;


public Polynomial() {
//creates polynomial 0
}

public Polynomial(double[] c) throws IllegalArgumentException{
//obtain coefficients
}

@Override
public int degree() {
 //return degree
}

@Override
public String toString() {
    //build polynomial

}}

Polynomial.java是我需要获取值的类。当我尝试这样做时,值总是返回&#39; null&#39;当它到达Polynomial类时。我被卡住了,不知道从哪里开始。谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

您应该实例化Polinomial对象并设置所需的值。

public class PolynomialDemo  {
public static int degree;
public static double[] numbers;

public static void main(String[] args) {

    //Create a Polynomial object
    Polynomial pol = new Polynomial();

    Scanner scan = new Scanner(System.in);
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter the degree of the first polynomial -> ");
    degree = scan.nextInt();

    System.out.print("Enter its coefficients in order of descending powers -> ");
    String deg = scanner.nextLine();
    String[] numbersStr = deg.split(" ");
    double[] numbers = new double[ numbersStr.length ];
    for ( int i = 0; i < numbersStr.length; i++ )
    {
        numbers[i] = Integer.parseInt( numbersStr[i] );
    }


    //Set values
    pol.setDegree(degree);
    pol.setCoefficients(numbers);

}

您需要在setDegree(int degree)课程中定义setCoefficients(double [] coeff)Polynomial

Setters,构造函数等是Java的基础知识。尝试寻找教程或阅读文档。另外,尝试模块化你的代码。