我无法弄清楚如何为我的if语句格式化代码。通常,我会从用户那里获取字符串输入并使用.equals,但是我需要使用的对象使这成为不可能。每当我打印数组的内容时,我都会得到引用。我想获取存储在数组中并在以后的代码行中打印的用户输入。
问题:如果可能的话,如何获取扫描器输入以分配给“团队”并在if语句中进行比较?我应该如何分配这些值?
这是我得到的代码
public class Team implements Comparable<Team> {
public String toString(String team, int wins) {
String winningStatement = team + ": " + wins;
return winningStatement;
}
// Data fields
private String name;
private int winCount;
Team() {
name = "Sooners";
winCount = 1;
}
Team(String inputName) {
name = inputName;
winCount = 1;
}
Team(String inputName, int inputWinCount) {
name = inputName;
winCount = inputWinCount;
}
这是我尝试使用ArrayList
Scanner scnr = new Scanner(System.in);
Random rando = new Random();
String name = "hi";
int cycles = 0;
int value = 0;
ArrayList<Team> teams = new ArrayList<Team>();
Team myTeam = new Team();
System.out.println("Welcome to the Advanced Sportsball Tracker!");
while (!name.equals("x")) // looping print statement
{ // x loop begins
System.out.println("Which team just won? (x to exit)");
name = scnr.next();
if (!teams.equals(name))
{
teams.add(thisTeam);
myTeam.setWinCount(1);
}
else if (teams.equals(name))
{
myTeam.incrementWinCount();
}
cycles++;
}// x loop ends
谢谢您的帮助
答案 0 :(得分:0)
仅根据示例的意图进行判断……看来这就是您要实现的目标。如前所述,您关于ArrayList对象如何与重载的构造函数相关的问题实际上没有道理
public class Team {
// Data fields
private String name;
private int winCount;
public Team() {
name = "Sooners";
winCount = 1;
}
public Team(String inputName) {
name = inputName;
winCount = 1;
}
Team(String inputName, int inputWinCount) {
name = inputName;
winCount = inputWinCount;
}
public String toString(String team, int wins) {
return team + ": " + wins;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWinCount() {
return winCount;
}
public void setWinCount(int winCount) {
this.winCount = winCount;
}
void incrementWinCount() {
winCount++;
}
}
void runSystem() {
List<Team> teams = new ArrayList<>();
Scanner scnr = new Scanner(System.in);
int cycles = 0;
System.out.println("Welcome to the Advanced Sportsball Tracker!");
System.out.println("Which team just won? (x to exit)");
String name = scnr.next();
while (!"x".equals(name)) {
final String teamName = name;
Team team = teams.stream().filter(t -> teamName.equals(t.getName())).findAny().orElse(null);
if (team == null) {
team = new Team(teamName, 1);
teams.add(team);
}
else {
team.incrementWinCount();
}
cycles++;
System.out.println("Which team just won? (x to exit)");
name = scnr.next();
}
}