我在试着创建一个梦幻橄榄球选秀节目。我遇到困难的第一步是正确地将数据读入列表。我要逐行扫描数据。我创建了一个循环来设置每个角色的名称,然后继续添加所有拥有该角色的人员,直到“-”出现在一行上。然后将该角色添加到角色列表中。我相信我的循环在这方面是正确的,但是,我不知道如何正确地使用Person构造函数,使其包含无法使用Person类中的setData方法实现的排名、名称和来源。我还是个编程新手,我想知道我是不是错过了什么。
数据文件
领导者
1个超人DC
2美国漫威队长
3 X Marvel教授
4《挖掘机神秘人》
布朗
1绿巨人漫威
2 Wolverine Marvel
3漫威
4 Beast Marvel
5雷神漫威
6“激情神秘人”
7不可思议的Pixar先生
...and等
主类
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class FantasyTeamDraft {
/**
* Joseph Simmons
* CPS 181
* February 6, 2013
*/
public static void main(String[] args) throws IOException{
Scanner scan = new Scanner (System.in);
System.out.println("Enter the name and location of the file wanted for the draft: ");
File draftData = new File (scan.next());
Scanner scanData = new Scanner(draftData);
List <Role> listOfRoles = new ArrayList <Role> ();
while (scanData.hasNext()) {
String line = scanData.nextLine();
if (!isInteger (line)) {
Role role = new Role ();
role.setRoleName(line);
String personLine = scanData.nextLine();
while (isInteger(personLine)){
Person person = new Person();
person.setData(personLine);
role.addPerson(person);
}
listOfRoles.add(role);
}
}
}
public static boolean isInteger (String line) {
try {
Integer.parseInt(line.split("\t") [0]);
} catch (NumberFormatException e) {
return false;
}
return true;
}}
Person类
import java.util.Scanner;
public class Person {
private int rank;
private String name;
private String origin;
public Person () {
}
public Person (int rank, String name, String origin) {
this.rank = rank;
this.name = name;
this.origin = origin;
}
public void setData (String line) {
String [] array = line.split("\t");
this.rank = Integer.parseInt(array [0]);
this.name = array [1];
this.origin = array [2];
}}
角色类
import java.util.List;
import java.util.Scanner;
public class Role {
private String roleName = "";
private List <Person> listOfPeople;
public Role (String roleName) {
this.roleName = roleName;
}
public void setRoleName (String line) {
this.roleName = line;
}
public String getRoleName() {
return roleName;
}
public void addPerson (Person person) {
this.listOfPeople.add(person);
}}
发布于 2013-02-12 10:35:01
在您的代码中,我看到
while (isInteger(personLine)){
Person person = new Person();
person.setData(personLine);
role.addPerson(person);
}如果isInteger(personLine)的计算结果为真,这将是无限循环。也许它应该是if而不是while,或者您需要在每次迭代中修改personLine。
发布于 2013-02-12 10:52:46
您有两个构造函数
公众人物() {
public Person (int rank, String name, String origin) {
this.rank = rank;
this.name = name;
this.origin = origin;
}如果我正确理解了您的问题,为了设置等级、名称和来源的值,您应该调用第二个构造函数。但是在你的循环中
while (isInteger(personLine)){
Person person = new Person();
person.setData(personLine);
role.addPerson(person);
}您在此处调用的是new Person(),请尝试将其更改为调用其他构造函数。
发布于 2013-02-12 12:58:52
创建一个接受字符串的构造函数,就像setData一样,然后在该构造函数中调用setData方法,将字符串发送给它。这样你就保留了setData,你的构造函数基本上就是setData()。
如果您希望完全保持构造函数的原样,则必须在main中拆分字符串
https://stackoverflow.com/questions/14824425
复制相似问题