以下代码是Android应用活动的一部分。我正在使用Jena(Androjena)来查询rdf文件。那部分工作正常。问题是我试图迭代结果并将其存储在二维数组中。列和行应该是这样的:
/////////////////
Adam /Sandler/43
Kate /Sandler/22
Mike /Jasonss/13
/////////////////
代码:
enter code here
// Query uses an external SPARQL endpoint for processing
// This is the syntax for that type of query
QueryExecution qe = QueryExecutionFactory.sparqlService(sparqlEndpointUri, query);
// Execute the query and obtain results
ResultSet resultSet = qe.execSelect();
// Setup a place to house results for output
StringBuffer results = new StringBuffer();
// Get the column names (the aliases supplied in the SELECT clause)
List<String> columnNames = resultSet.getResultVars();
int i=0;
int j=0;
String results1[][] = new String[i][j];
// Iterate through all resulting rows
while (resultSet.hasNext()) {
// Get the next result row
QuerySolution solution = resultSet.next();
results1 = new String[i][columnNames.size()];
// Iterate through the columns
for (String var : columnNames) {
// Add the column label to the StringBuffer
results.append(var + ": ");
// Add the returned row/column data to the StringBuffer
// Data value will be null if optional and not present
if (solution.get(var) == null) {
results.append("{null}");
// Test whether the returned value is a literal value
} else if (solution.get(var).isLiteral()) {
results.append(solution.getLiteral(var).toString());
results1[resultSet.getRowNumber()][j]=solution.getLiteral(var).toString();
j++;
// Otherwise the returned value is a URI
} else {
results.append(solution.getResource(var).getURI().toString());
results1[resultSet.getRowNumber()][j]=solution.getResource(var).getURI().toString();
j++;
}
results.append('\n');
}
results.append("-----------------\n");
i++;
}
PS。忽略字符串缓冲区。
答案 0 :(得分:1)
由于您事先并不知道结果集的大小,因此无法使用数组。当您从resultSet中读取行时,请使用ArrayList<String[]>
并将String[]
元素添加到列表中。
ArrayList<String[]> results1 = new ArrayList<>();
当您阅读完所有行后,如果需要,仍然可以按索引引用行和列,使用
results1.get(index)[colIndex]
答案 1 :(得分:0)
问题是您创建的数组实际为String results1[][] = new String[i][j];
String results1[][] = new String[0][columnNames.size()];
然后在for (String var : columnNames)
循环中增加i的值并尝试将元素设置为results1[resultSet.getRowNumber()][j]
。
上面你说它是一个0,columnNames.size()
数组,在循环中你尝试访问resultSet.getRowNumber(), j
。 j
在这里是合法的,但resultSet.getRowNumber()
不是。