我想将字符串矩阵的对角线检索到单独的列表中。请帮我。我整天都在上面。但没有成功。
二维数组结构:
Matrix{{"Toyata","Fortuner","Price", "tuesday", "deliver", "Working"},
{ "Ford","Classic ","Price", "Wedday", "Not Deliver", "Working"},
{"Tata","Jaguar","Price", "Satday", "deliver", "Working" }
{"Farari","etc","Price", "sunday", "deliver", "NotWorking" }
我想从矩阵上方检索第一行和第三行。即
{"Toyata","Fortuner","Price", "tuesday", "deliver", "Working"},
{"Tata","Jaguar","Price", "Satday", "deliver", "Working" }
这是我的代码:
public Object[][] geCodes(){
Object [][] Matrix{
{"Toyata","Fortuner","Price", "tuesday", "deliver", "Working"},
{ "Ford","Classic ","Price", "Wedday", "Not Deliver", "Working"},
{"Tata","Jaguar","Price", "Satday", "deliver", "Working" }
{"Farari","etc","Price", "sunday", "deliver", "NotWorking" }};
Object Diagonal1=null;
List<Object> che= new LinkedList<Object>();
for (int i = 0, j =0; i< matrix.length && j < matrix[0].length; i++, j++) {
Diagonal1= matrix[i][j];
che.add(Diagonal1);
}
System.out.println("*******"+che);
return matrix;
}
答案 0 :(得分:1)
您没有说自己的想法。对角表示第一行的第一个元素,第二行的第二个元素……最后一行的最后一个元素。
您进行一个循环并获得矩阵[i] [i]的位置。您不需要“ i”和“ j”,因为它们是相同的。
如果要获得第一行和第二行,那么就这样做。
Object[][] matrix2 = new Object[2][6];
matrix2[0] = Matrix[0];
matrix2[1] = Matrix[2];
您的代码:
public Object[][] geCodes(){
Object [][] Matrix{
{"Toyata","Fortuner","Price", "tuesday", "deliver", "Working"},
{"Ford","Classic ","Price", "Wedday", "Not Deliver", "Working"},
{"Tata","Jaguar","Price", "Satday", "deliver", "Working" }
{"Farari","etc","Price", "sunday", "deliver", "NotWorking" }};
Object[][] Diagonal1= new Object[2][6];
Diagonal1[0] = Matrix[0];
Diagonal1[1] = Matrix[2];
return matrix; // I don't know why you are returning matrix,
// you probably should be returning the new array, Diagonal1
}
您确实应该使用字符串而不是对象。
答案 1 :(得分:-1)
如果您想要对角线还是第一个和第三个对角线,我真的不明白,但这是一个示例:
String[][] matrixStart = {
{"Toyata", "Fortuner", "Price", "tuesday", "deliver", "Working"},
{"Ford", "Classic", "Price", "Wedday", "Not Deliver", "Working"},
{"Tata", "Jaguar", "Price", "Satday", "deliver", "Working"},
{"Farari", "etc", "Price", "sunday", "deliver", "NotWorking"}};
List<String[]> matrixEnd = new LinkedList<>();
for(int i = 0; i < matrixStart.length; i++)
{
if(i == 1 || i == 3)
{
matrixEnd.add(matrixStart[i]);
}
}
// Printing what's in your matrixEnd
System.out.println("MatrixEnd :");
String sysout;
for(String[] line: matrixEnd)
{
sysout = "";
for(String element: line)
{
sysout += element + ", ";
}
System.out.println("[" + sysout.substring(0, sysout.length() - 2) + "]");
}
最后,您会得到类似:
MatrixEnd :
[Ford, Classic, Price, Wedday, Not Deliver, Working]
[Farari, etc, Price, sunday, deliver, NotWorking]
此外,您应该使用String而不是Objects并用小写字母命名变量,最后打印“ che”将不会打印内部内容,而只会打印引用,除非您为LinkedList覆盖toString()。