簡體   English   中英

我怎樣才能得到從另一個類返回的整數?

[英]How can I get the ints returned from another class?

我在計算機數學課程中有一個項目,我們需要輸入 3 個系數 (ax^2 + bx + c) 並使用二次公式計算零。 這對我們來說不會太難,但我們必須將工作拆分為不同的資源類和驅動程序類。

大綱: https : //imgur.com/a/0Mn3m

到目前為止,這是我迄今為止所擁有的

import java.util.Scanner;

public class coEff
{
    public int coEff()
    {

        int a, b, c;
        double root1, root2, root3, d;

        Scanner s = new Scanner(System.in);

        System.out.print("Enter the A coefficient");
        a = s.nextInt();

        System.out.print("Enter the B coefficient");
        b = s.nextInt();

        System.out.print("Enter the C coefficient");
        c = s.nextInt();

        return coEff();

    }

}

第二類:

import java.util.Scanner;

public class calcZeroes
{
    public int calcZeroes()
    {
        coEff coEff = new coEff();
        coEff.coEff();

        int a, b, c;
        double root1, root2, root3, d;

        return calcZeroes();
    }
}

我有計算公式的代碼,但它不起作用,因為系數沒有初始化。 任何幫助,將不勝感激 :)

您將在每堂課結束時返回您的班級名。 它只會遞歸地調用你的類。 (甚至可能會出錯,我以前沒有嘗試過)。 在您的情況下,您應該只返回一個 int 值。 例如

`int something = 0;
 return something;`

我假設您是 Java 新手,因為您的整個類結構都是亂序的。 對於初學者,Bami 建議您返回班級名稱。 在 Java 中,“多態”的概念描述了一種語言通過單個統一接口處理各種類型和類對象的能力。 所以你可以創建 coEff 類並在那里進行計算並在驅動程序類中獲取用戶輸入。 您可以將驅動程序類中的變量作為參數傳遞給 coEff 方法。

  import java.util.Scanner;

  public class coEff{

  public int coEff(int a, int b, int c){
  int result;

  //do the calculation here.

  return result;
  }
}

在您的驅動程序類中,您獲取輸入並使用 coEff 對象將這些輸入作為參數傳遞給您的 coEff 方法。

 import java.util.*;

 public class Driver{

 public static void main(String [] args){
  int a,b,c;
  Scanner input = new Scanner(System.in);

  System.out.println("Enter co-efficient A:\n");
  a = input.nextInt();

  System.out.println("Enter co-efficient B:\n");
  b = input.nextInt();

  System.out.println("Enter co-efficient C:\n");
  c = input.nextInt();

  coEff coeff = new coEff();

  System.out.println(coEff.coEff(a,b,c));
 }
 }

附帶說明:不要對類和方法使用相同的名稱,除非它是構造函數。

編輯:如果您需要在單獨的類中獲取輸入,您仍然可以使用相同的概念,而不是在驅動程序中獲取輸入,只需將其放入不同的類中並調用 coEff 方法並在驅動程序中打印結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM