一群朋友和我正在进行秘密的圣诞老人交流,我决定制作一个程序来随机化并打印一份我将拥有的主列表,以获得乐趣。这是我到目前为止所拥有的。我对第String random1 = sList.get(myRandomizer.nextInt(sList.size()));
行
它给出的错误是我做了不兼容的类型,但我很确定它会返回它应该做的事情吗?
这是我的初级课程
import java.io.Serializable;
public class SpecifiedData implements Serializable
{
private String name;
public SpecifiedData(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}
这是我的测试类,我的错误是
import java.util.*;
import java.io.*;
public class Randomizer
{
public static void main(String[] args) throws IOException, ClassNotFoundException
{
Random myRandomizer = new Random();
boolean done = false;
ArrayList<SpecifiedData> sList = new ArrayList<SpecifiedData>();
File sFile = new File("Participants.dat");
if(sFile.exists())
{
FileInputStream myFIS = new FileInputStream(sFile);
ObjectInputStream sIn = new ObjectInputStream(myFIS);
sList = (ArrayList<SpecifiedData>)sIn.readObject();
sIn.close();
}
do
{
Scanner myScanner = new Scanner(System.in);
while (!done)
{
System.out.println("1 - add a person");
System.out.println("2 - display all people");
System.out.println("3 - delete person");
System.out.println("4 - randomize");
System.out.println("5 - exit");
int choice = Integer.parseInt(myScanner.nextLine());
if (choice == 1)
{
System.out.print("Enter person's name: ");
String participantsName = myScanner.nextLine();
SpecifiedData mySpecifiedData = new SpecifiedData(participantsName);
sList.add(mySpecifiedData);
}
else if (choice == 2)
{
for(int i = 0; i < sList.size(); i++)
System.out.println(sList.get(i).getName());
}
else if (choice == 3)
{
System.out.println("Enter persons name: ");
String participantsName = myScanner.nextLine();
for(SpecifiedData mySpecifiedData : sList)
{
if(mySpecifiedData.getName().equals(participantsName))
{
sList.remove(mySpecifiedData);
break;
}
}
}
else if (choice == 4)
{
for(int i = 0; i < (sList.size()/2); i++)
{
for(SpecifiedData mySpecifiedData : sList)
{
String random1 = sList.get(myRandomizer.nextInt(sList.size()));
if(mySpecifiedData.getName().equals(random1))
{
System.out.println(random1 + " ");
sList.remove(random1);
break;
}
String random2 = sList.get(myRandomizer.nextInt(sList.size()));
if(mySpecifiedData.getName().equals(random2))
{
System.out.print(random2);
sList.remove(random2);
break;
}
}
}
}
else if(choice == 5)
{
done = true;
}
else
System.out.println("Invalid menu choice!");
}
System.out.println("Goodbye!");
}while(!done);
FileOutputStream myFOS = new FileOutputStream(sFile);
ObjectOutputStream sOut = new ObjectOutputStream(myFOS);
sOut.writeObject(sList);
sOut.close();
}
}
答案 0 :(得分:0)
sList被声明为包含SpecifiedData类型对象的ArrayList。在该行上,您将从列表中获取一个对象并尝试将其分配给String。您需要将其分配给SpecifiedData。
SpecifiedData random1 = sList.get(myRandomizer.nextInt(sList.size()));
答案 1 :(得分:0)
sList
是SpecifiedData
类型的列表,而不是String
,因此此错误完全正常。顺便说一下,你正在从你正在遍历的列表中删除元素......糟糕的主意。我没有仔细查看你的代码,但有一件事是肯定的:你必须改进它。