两个 do while 循环真的让我很困惑..
我创建了一个函数,用于与sql中的数字进行匹配。如果用户输入的值存在,则加1。保存用户输入值的(Object[] array)
并与sql中的值进行比较。 sql中有两行。
该程序应该像这样工作:
(Object[] array) // assuming it holds
[2,3]
Object[] array1 // holding
[1,2,3,0,0] and [2,5,6,0,0]
Output : 2 1
但是我无法获得任何输出...我的代码有什么问题?
我很确定错误来自 CountMatching(Object[] array, Object[] array1)
public void ComparePre(Object[] array) throws Exception {
String sql="Select Pre1,Pre2,Pre3,Pre4,Pre5 from preferences ";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
Object[] b=new Object[5];
while (rs.next()) {
Vector r = new Vector(); // sql data to vector
r.add(rs.getInt("Pre1"));
r.add(rs.getInt("Pre2"));
r.add(rs.getInt("Pre3"));
r.add(rs.getInt("Pre4"));
r.add(rs.getInt("Pre5"));
System.out.println(r);
Object[] array1 = new Object[5];
r.copyInto(b);
}
CountMatching(array,b);
ps.close();
rs.close();
conn.close();
}
private void CountMatching(Object[] array, Object[] array1) {
int count=0;
int a=0;
do {
int b=0;
do {
if(array[a]==array1[b]) {
count++;
} else if(array[a]!=array1[b]) {
b++;
}
} while(b<array1.length);
a++;
} while (a<array.length);
System.out.println(count);
}
最佳答案
我发现此方法至少有两个问题:
- 两个嵌套的
do { ... } while ()
循环可能会导致无限循环。也就是说,如果在任何时候array[a]==array1[b]
为真,内部计数器b
将永远不会增加(即b++
) code> 从未被调用)。 - 如果其中一个数组的长度为
0
,则此方法将抛出IndexOutOfBoundsException
在当前形式中,如果两个数组都不为空(长度> 0)并且找不到实际匹配项,则该方法只会执行其预期的操作。
显式的 for
循环可能会阻止这种情况,如果这是您需要的:
private void CountMatching(Object[] array, Object[] array1) {
int count = 0;
for (int a = 0; a < array.length; a++) {
for (int b = 0; b < array1.length; b++) {
if (array[a] == array1[b]) {
count++;
}
}
}
System.out.println(count);
}
或者,如果您不需要其他任何特定索引:
private void CountMatching(Object[] array, Object[] array1) {
int count = 0;
for (Object arrayEntry : array) {
for (Object array1Entry : array1) {
if (arrayEntry == array1Entry) {
count++;
}
}
}
System.out.println(count);
}
<小时/>
在当前代码中,r.copyInto(b)
始终会覆盖之前数组中的内容,因此您只能得到最后一个结果行:
Object[] b=new Object[5];
while (rs.next()) {
Vector r = new Vector(); // sql data to vector
r.add(rs.getInt("Pre1"));
r.add(rs.getInt("Pre2"));
r.add(rs.getInt("Pre3"));
r.add(rs.getInt("Pre4"));
r.add(rs.getInt("Pre5"));
System.out.println(r);
Object[] array1 = new Object[5];
r.copyInto(b);
}
CountMatching(array,b);
最简单的方法是将 CountMatching(array,b)
向上移动一行(即进入 while 循环)。
关于java - 两个do while循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32163974/