如何在 JTextArea java 和 Array.sort 中以降序和升序显示矩阵?
How to display a matrix in a descending and ascending form in a JTextArea java with Array.sort?
我需要按降序和升序对矩阵进行排序,但将其打印为一维数组。
目前它按升序排序,但只有最后一行,我不知道如何显示所有行,也不知道如何按降序排序。
public void mostrarMatriz (int matriz[][], int n){
DefaultTableModel model = (DefaultTableModel) tablaMatriz.getModel();
model.setRowCount(n);
model.setColumnCount(n);
for(int i = 0; i < n ; i++){
for(int j = 0; j < n; j++){
tablaMatriz.setValueAt(matriz[i][j], i, j);
}
}
for(int[] i: matriz){
Arrays.sort(i);
txtMenor.setText(Arrays.toString(i));
}
}
}
文本中只显示矩阵的最后一行的原因是每次迭代都会被覆盖,例如:
// text is being set/overwritten in each iteration of this loop
for(int[] i : matriz) {
Arrays.sort(i);
txtMenor.setText(Arrays.toString(i));
}
// You can use append instead
String text = "";
for(int[] i : matriz) {
Arrays.sort(i);
text += Arrays.toString(i) + " ";
}
txtMenor.setText(text);
要按降序显示每一行,您必须在将每个数组附加到文本之前按相反的顺序对其进行排序。您可以使用流:
// You can use append instead
String text = "";
for(int[] i : matriz) {
int[] sorted = IntStream.of(i)
.boxed()
.sorted(Comparator.reverseOrder())
.mapToInt(a -> a)
.toArray();
text += Arrays.toString(sorted) + " ";
}
txtMenor.setText(text);
循环应该附加文本,而不是在每次迭代时重置它:
String text="";
for(int[] i: matriz)
{
Arrays.sort(i);
text+=Arrays.toString(i)+" ";
}
if (!text.isEmpty())
txtMenor.setText(text.subString(0,text.length()-1));
相反的顺序,只是翻转它之后:
Collections.reverse(Arrays.asList(matriz));
txtX.setText(Arrays.deepToString(matriz));
我需要按降序和升序对矩阵进行排序,但将其打印为一维数组。
目前它按升序排序,但只有最后一行,我不知道如何显示所有行,也不知道如何按降序排序。
public void mostrarMatriz (int matriz[][], int n){
DefaultTableModel model = (DefaultTableModel) tablaMatriz.getModel();
model.setRowCount(n);
model.setColumnCount(n);
for(int i = 0; i < n ; i++){
for(int j = 0; j < n; j++){
tablaMatriz.setValueAt(matriz[i][j], i, j);
}
}
for(int[] i: matriz){
Arrays.sort(i);
txtMenor.setText(Arrays.toString(i));
}
}
}
文本中只显示矩阵的最后一行的原因是每次迭代都会被覆盖,例如:
// text is being set/overwritten in each iteration of this loop
for(int[] i : matriz) {
Arrays.sort(i);
txtMenor.setText(Arrays.toString(i));
}
// You can use append instead
String text = "";
for(int[] i : matriz) {
Arrays.sort(i);
text += Arrays.toString(i) + " ";
}
txtMenor.setText(text);
要按降序显示每一行,您必须在将每个数组附加到文本之前按相反的顺序对其进行排序。您可以使用流:
// You can use append instead
String text = "";
for(int[] i : matriz) {
int[] sorted = IntStream.of(i)
.boxed()
.sorted(Comparator.reverseOrder())
.mapToInt(a -> a)
.toArray();
text += Arrays.toString(sorted) + " ";
}
txtMenor.setText(text);
循环应该附加文本,而不是在每次迭代时重置它:
String text="";
for(int[] i: matriz)
{
Arrays.sort(i);
text+=Arrays.toString(i)+" ";
}
if (!text.isEmpty())
txtMenor.setText(text.subString(0,text.length()-1));
相反的顺序,只是翻转它之后:
Collections.reverse(Arrays.asList(matriz));
txtX.setText(Arrays.deepToString(matriz));