簡體   English   中英

當返回值每次在新程序中運行時,其值都應更改時,從另一個Java類調用方法

[英]Calling a method from another Java class when return value should change every time it is run in the new program

我是Java的初學者,正在嘗試制作兩個不同的程序,但是在將數據從一個轉移到另一個時遇到了問題。

第一個程序就像一個隨機數生成器。 看起來像這樣(簡化但思路相同):

public class Tester{
  public static double num;
  public static void main(String[] args){
    double n;
    n = Math.random() * 100;
    System.out.println(n);
    num = n;
  }
  public static double gen(){
    return num;
  }
}

然后,我試圖調用該函數並打印n個隨機數並將它們全部放入列表中。 該程序如下所示:

public class lister{
  public static void main(String[] args){
    //declare
    int n,counter;
    double[] list;
    double num;
    //initialize
    n = Integer.parseInt(args[0]);
    list = new double[n];
    counter = 0;
    double num = Tester.gen();
    //add all generated numbers to a list, print them
    while (counter < n){
      num = Tester.gen();
      list[counter] = num;
      System.out.println(num);
      ++counter;
    }
  }
}

但是num最終每次都是0.0。 我試過不使其靜態化,但是隨之而來的卻是它自己的一系列問題,據我所知,靜態並不意味着不可更改。

如何解決此問題,以便在每次while循環運行時使num為新數字? 那有可能嗎?

這是建議的答案:

public class Tester {
public static double gen(){
    double n;
    n = Math.random() * 100;
    return num;
  }
}

public class lister{
  public static void main(String[] args){
    //declare
    int n,counter;
    double[] list;
    double num;
    //initialize
    n = Integer.parseInt(args[0]);
    list = new double[n];
    counter = 0;
    double num = Tester.gen();
    //add all generated numbers to a list, print them
    while (counter < n){
      num = Tester.gen();
      list[counter] = num;
      System.out.println(num);
      ++counter;
    }
  }
}

如果運行列表類main(),則不會調用Tester類的main()方法,因此Math.random()永遠不會運行。 嘗試這個 :

public class Tester{
  public static double gen(){
    return Math.random() * 100;
  }
}

問題是,你永遠不會調用Tester.main()lister.main()你只需要調用Tester.gen()方法),所以既然喜歡的實例變量雙Tester.num總是初始化為0.0的值,除非你給它分配一個不同的值,每次使用它時,總是在lister.main()獲得該值。

您的代碼應該通過Tester.gen()調整Tester.gen()來工作,因此它實際上是一個返回隨機數的代碼,如下所示:

public static double gen(){
    return Math.random() * 100;
}

之后,您的代碼應該可以正常工作。

除此之外, Tester.main()沒有用,因為您已經在使用/運行列表器,並且只能使用一個main()作為Java SE應用程序的入口點。

暫無
暫無

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

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