gpt4 book ai didi

java - 将多个数组返回给main方法

转载 作者:行者123 更新时间:2023-12-01 14:04:19 24 4
gpt4 key购买 nike

我的程序假设获取一个文本文件,读取前四个名字,创建一个 1-4 之间的随机数,然后根据随机数将名字分配给 4 个不同的团队。例如,如果数字是 3,那么第一个名字将属于第 3 队,第二个名字将属于第 4 队,等等(重复过程,直到没有更多的名字)我相信我拥有正确的所有代码,问题是我不知道如何返回放入方法中的数组中的所有名称。这是我的代码:

public static void main(String args[]) throws IOException
{
BufferedReader girlFile = new BufferedReader(new FileReader("girls40.txt"));
PrintWriter teamFile = new PrintWriter(new FileWriter("xxxxxxx-teamlist.txt"));
String team1[] = new String[20];
String team2[] = new String[20];
String team3[] = new String[20];
String team4[] = new String[20];
int n;

n = loadTeams(team1,team2,team3,team4,girlFile);
girlFile.close();
teamFile.close();
}

public static String[] loadTeams(String team1[],String team2[],String team3[],String team[],BufferedReader girlFile)
{
int n;
int random;
String name1;
String name2;
String name3;
String name4;
while((name1=girlFile.readLine())!=null)
{
name2=girlFile.readLine();
name3=girlFile.readLine();
name4=girlFile.readLine();
random = 1 + (int)(Math.random() * 4);
if(random==1)
{
team1[n]=name1;
team2[n]=name2;
team3[n]=name3;
team4[n]=name4;
}
if(random==2)
{
team1[n]=name4;
team2[n]=name1;
team3[n]=name2;
team4[n]=name3;
}
if(random==3)
{
team1[n]=name3;
team2[n]=name4;
team3[n]=name1;
team4[n]=name2;
}
if(random==4)
{
team1[n]=name2;
team2[n]=name3;
team3[n]=name4;
team4[n]=name1;
}
n++;
}
return team1[],team2[],team3[],team4[];
}`

main方法是给我的,所以不能改变。

最佳答案

如果 main 方法中的代码比您在此处发布的代码多。您必须提及变量 n 是什么以及它是如何使用的,否则请遵循答案。

main方法无法更改

在你的主要方法中,

int n;

n = loadTeams(team1,team2,team3,team4,girlFile);
girlFile.close();
teamFile.close();
} // End of Main Method

您没有无缘无故地使用返回值n。因此,从方法 loadTeams() 返回什么并不重要,只要它是 int 即可。

此外,这里 loadTeams() 返回一个 String[],它不能被分配为 int n,你必须将 loadTeams() 的返回类型更改为 int as

public static int loadTeams(String team1[],String team2[],String team3[],String team[],BufferedReader girlFile) {
/*
...
*/
return 0; // whatever, it isn't being used
}

如果您无法更改 main 方法,这就是解决方案。

关于java - 将多个数组返回给main方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19045684/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com