繁体   English   中英

在Java中将用户输入的数字从一类引用到另一类

[英]Referencing user inputted numerics from one class to another in Java

我在TestQuadraticEquations类中创建的引用导致空值,因此,当我尝试将它们发送到我创建的另一个类时,该程序没有任何值来分配变量。

变量的打印语句只是为了测试是否分配了任何东西,不幸的是,什么都没有分配。 任何意见,将不胜感激。

public class TestQuadraticEquation {
public static void main(String[]args) {
    TestQuadraticEquation nums = new TestQuadraticEquation();
    nums.promptForNum();
    TestQuadraticEquation getCo = new TestQuadraticEquation();
    int a1 = getCo.getA();
    int b1 = getCo.getB();
    int c1 = getCo.getC();
    System.out.println(a1 + " " + b1 + " " + c1);
    Equation solution1 = new Equation();
    System.out.println("For: " + solution1.getA2() + "x\u00B2 + " + 
            solution1.getB2() + "x + " + solution1.getC2());
    if (solution1.getDiscriminant() > 0) {
        System.out.println("Roots are: " + solution1.getRoot1() + " " + 
                solution1.getRoot2());
    }
    else if (solution1.getDiscriminant() == 0) {
        System.out.println("Roots are: " + solution1.getRoot1());
    }
    else{
        System.out.println("No roots.");
    }  
}
Scanner in = new Scanner(System.in);
private int a;
private int b;
private int c;
public void promptForNum() {
    System.out.println("Enter three coefficicents: ");
    a = in.nextInt();
    b = in.nextInt();
    c = in.nextInt();
}
public int getA() {
    return a;
}
public int getB() {
    return b;
}
public int getC() {
    return c;
}
}

您的问题,从事实的情况下茎TestQuadraticEquation称为nums是从实例不同TestQuadraticEquation称为getCo 因此,当您调用nums.promptForNum() ,您正在将值插入实例“ nums”内部的私有变量中。

如果不是获取全为0的getCo值,而是获取nums的值,则将获取所需的值。

int a1 = nums.getA();
int b1 = nums.getB();
int c1 = nums.getC();
System.out.println(a1 + " " + b1 + " " + c1);

暂无
暂无

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

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