代码:
public static int getBalance()
{
List <Integer> sum = new ArrayList<Integer>();
int balance=0;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/money","root","cpp");
PreparedStatement ps = con.prepareStatement("select * from account");
ResultSet rs = ps.executeQuery();
while(rs.next())
{
sum.add(Integer.parseInt(rs.getString(1)));
for(int i:sum)
{
balance += i;
}
}
}
}
显示金额时,它已加倍 例如,如果2000仅是当前金额,则当前余额为4000
答案 0 :(得分:1)
对于找到的每个结果,您都执行一次此操作,因此,如果有两个结果,则金额将相加两次:
for(int i:sum)
{
balance+=i;
}
尝试将该块移出while
语句。您可以在此处了解有关while
的更多信息:https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html