我通过从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”)那么它做的是从第一个结果数组然后假设数组中的每个其他项都是相同的。
不知道我哪里出错了,有什么想法吗?
答案 0 :(得分:0)
您正在列表中添加对象,但在迭代结果时不会在任何地方初始化对象。
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
}
答案 1 :(得分:0)
您正在使用null值初始化引用,首先要创建对象,然后将其中的值设置为
HomeTeamResults hometeamResults= null;
while (rs.next())
{ hometeamResults=new HomeTeamResults()
hometeam = rs.getString("HomeTeam");
awayteam = rs.getString("AwayTeam");
result = rs.getString("Result");
hometeamResults.setHomeTeam(hometeam);
hometeamResults.setAwayTeam(awayteam);
hometeamResults.setResult(result);
allResults.add(hometeamResults);
}