【发布时间】:2012-06-28 10:18:05
【问题描述】:
这个问题与我对另一个问题的回答有关。 原问题是here
谁能解释为什么错误代码会按照 cmets 中解释的方式失败(因为它是伪代码)
// bad code
ResultSet rs = getDataFromDBMS("Select * from [tableName];");
//temp uses a collection member within it to hold a list of column names to data value pairs (hashmap<String,String>)
Object temp = new objectToHoldInfoFromResultSet();
// loop over the result set
while (rs.next)// for each row in the result set
{
for (int i = 1; i <= rs.getNumberColums; i++) {
temp.add(infoAboutColumn);
}
temp.printInfo();// always prints correct (ie current) info
//the print just takes the hashmap member and asks for a
//toString() on it
anotherObject(makeUseOf(temp));// always uses info from first
//iteration. Essentially grabs the hashMap member of temp, and puts
//this into another collection of type
//HashMap< HashMap<String,String>, temp> see the linked question
//for more detail.
}
// Seemingly each loop into the while the temp.doSomethingToData(); uses
// the temp object created in the first iteration
// good code
ResultSet rs = getDataFromDBMS("Select * from [tableName];");
// loop over the result set
while (rs.next)// for each row in the result set
{
Object temp = new objectToHoldInfoFromResultSet();// moving
// declaration
// of temp into
// the while
// loop solves
// the problem.
for (int i = 1; i <= rs.getNumberColums; i++) {
temp.add(infoAboutColumn);
}
temp.printInfo();// always prints correct (ie current) info
anotherObject(makeUseOf(temp));// also uses the correct (ie current)
// info.
}
【问题讨论】:
-
嗯,你在这里遇到什么问题?
-
老兄。我们必须找到问题并解决答案吗??
-
把整个问题放在这里,不要把其他问题的答案发给我们。
-
您发布的代码有很多缺陷,最糟糕的可能是它不是有效的Java。您正在给那些想要帮助您完成任务的人增加负担,而这些任务是您作为提问者的责任。
-
我很欣赏您的 cmets,但似乎下面的 Peter Torok 能够理解我的问题,并提供了一个我认为令人满意的答案。 @AkhilDev 哈哈,确实,我有一个答案,但它提出了一个新问题,所以为了简洁起见,我剪掉了我的答案。 Marko Topolnik:对不起,我可能应该说我提供的是“伪代码”,我从来没有说过它是 java,除了标签,因为我知道代码不是好的 java
标签: java while-loop