![](/img/trans.png)
[英]Trouble with methods from one class interacting with methods in another class
[英]Call one class' methods from another class
這是我當前的代碼:
如何將方法調用到其他類?
import java.util.Random;
public class WordSelect {
private Random r;
public void selectHundred(String[]w5000, String[] w100) {
r = new Random();
int i = 0;
while (i < w100.length) {
int random = r.nextInt(w5000.length);
w100[i] = w5000[random];
i++;
}
}
}
是否要創建WordSelect的對象並從其他類調用selectHundred方法? 如果是這樣,您可以執行以下操作
//This should be in the MainClass.java file
package test;
public class MainClass {
public static void main(String[] args) {
WordSelect ws = new WordSelect();
String[] w5000 = new String[10];//replace this and the following 10 lines with your w5000
w5000[0] = "a";
w5000[1] = "b";
w5000[2] = "c";
w5000[3] = "d";
w5000[4] = "e";
w5000[5] = "f";
w5000[6] = "g";
w5000[7] = "h";
w5000[8] = "i";
w5000[9] = "j";
String[] w100 = ws.selectHundred(w5000); // I believe you already have w5000, and you will the 100 random words in the w100
for(int i=0;i<w100.length;i++) {
System.out.println(w100[i]);
}
}
}
但是您需要將現有程序更改為以下內容,以便該方法可以返回100個字符串的數組
//This should be in the WordSelect.java file
package test;
import java.util.Random;
public class WordSelect {
private Random r;
public String[] selectHundred(String[]w5000) {
r = new Random();
int i = 0;
String []w100 = new String [5];
while (i < w100.length) {
int random = r.nextInt(w5000.length);
w100[i] = w5000[random];
i++;
}
return w100;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.