[英]How do I use value from one class for another class Calling from main method
[英]How do you obtain a value from the main method to use in another class?
我目前正在编写一个程序,以获取用户输入的多项式的系数和次数,然后将这些输入转换为多项式。 在我的主要方法中,我使用扫描仪获取一行字符串,然后将其转换为双精度数组。 但是,我需要在另一个类中使用此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] );
}
多项式
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是我需要在其中获取值的类。当我尝试执行该操作时,该值在进入Polynomial类时始终返回“ null”。 我被困住了,不知道从这里去哪里。 谢谢您的帮助!
您应该实例化一个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);
}
您需要在Polynomial
类中定义setDegree(int degree)
和setCoefficients(double [] coeff)
。
设置器,构造器等都是Java的基础。 尝试查找教程或阅读文档。 另外,尝试模块化您的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.