gpt4 book ai didi

java - 遍历数组并检查项目的值

转载 作者:行者123 更新时间:2023-11-30 00:38:45 25 4
gpt4 key购买 nike

我通过从 mysql 表中获取数据来填充一个数组,我想做的是迭代该数组,检查每个项目的值,然后根据该值执行不同的操作。

这是我连接到数据库并尝试迭代数组的方法的代码

public void HomeRecord(){

ArrayList<HomeTeamResults> allResults = new ArrayList<>();

try
{
//Sets up the connedtion to the database and installs drivers which are required.

Class.forName("com.mysql.jdbc.Driver");

con = DriverManager.getConnection("jdbc:mysql://localhost", "username", "password");


String table = box1.getSelectedItem().toString();
String SQL = "SELECT * FROM " + table + " WHERE `HomeTeam` = ?";
PreparedStatement prepst;

prepst = con.prepareStatement(SQL);
prepst.setString(1,box1.getSelectedItem().toString());
rs = prepst.executeQuery();

HomeTeamResults hometeamResults=null;
while (rs.next())
{
hometeam = rs.getString("HomeTeam");
awayteam = rs.getString("AwayTeam");
result = rs.getString("Result");


custs = (hometeam + "," + awayteam + "," + result);
allResults.add(hometeamResults);
}

}

catch (Exception e)
{
System.out.println("Error " +e);
}

System.out.println("Size of HomeArrayList::"+allResults.size());
for(HomeTeamResults temp:allResults){

if(temp.getResult().equals("W")){
hometeamvalue = hometeamvalue + 50;
}

else if(temp.getResult().equals("D")){
hometeamvalue = hometeamvalue + 10;
}

else
{
hometeamvalue = hometeamvalue + 0;
}

}

}

这是数组的代码

public class HomeTeamResults {   

private String hometeam;
private String awayteam;
private String result;

public String getHomeTeam() {
return hometeam;
}

public void setHomeTeam(String hometeam) {
this.hometeam = hometeam;
}

public String getAwayTeam() {
return awayteam;
}

public void setAwayTeam(String awayteam) {
this.awayteam = awayteam;

public String getResult() {
return result;
}

public void setResult(String result) {
this.result = result;
}

private HomeTeamResults(String hometeam, String awayteam, String result)
{
this.hometeam = hometeam;
this.awayteam = awayteam;
this.result = result;

}

@Override
public String toString()
{
return " "+hometeam+", "+awayteam+", "+result;
}
}

我遇到的问题是比较。当我尝试 if(temp.getResult().equals("W") 时,它根本不起作用。如果我尝试 if(result.equals("W") ,那么它所做的就是获取第一个结果数组,然后假设数组中的所有其他项都是相同的。

不知道我哪里出错了,有什么想法吗?

最佳答案

您正在列表中添加对象,但在迭代结果时未在任何地方初始化该对象。

HomeTeamResults hometeamResults=null;  // Object is null
while (rs.next())
{
hometeam = rs.getString("HomeTeam");
awayteam = rs.getString("AwayTeam");
result = rs.getString("Result");
custs = (hometeam + "," + awayteam + "," + result); // No idea abt usage
hometeamResults = new HomeTeamResults(hometeam,awayteam,result); // Initial It
allResults.add(hometeamResults); // Now List will contain proper object
}

关于java - 遍历数组并检查项目的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21959804/

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