2015-04-26 19 views
0

初學者程序員對我一無所知。在Java中引用用戶從一個類輸入到另一個類的數字

我在TestQuadraticEquations類中創建的引用會產生空值,所以當我嘗試將它們發送給另一個類時,我創建的程序沒有任何值來分配變量。

該變量的print語句只是爲了測試是否有任何東西被分配,遺憾的是,沒有東西。任何意見,將不勝感激。

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; 
} 
} 

回答

0

您的問題,從一個事實,即TestQuadraticEquation稱爲nums實例是從名爲getCoTestQuadraticEquation實例不同造成的。因此,當您撥打nums.promptForNum()時,您正在將值插入到實例'nums'中的私有變量中。

如果不是抓取值爲getCo(全爲0),而是抓取nums的值,則會得到您正在查找的值。

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