[英]Print Specific Row in 2D Array
How would I get just the second row to print in this 4x4 array? 我如何才能在该4x4阵列中仅打印第二行?
double [][] table = new double[4][4];
for(int i = 0; i < table.length; i++){
for(int j = 0; j < table[i].length; j++)
table[i][j] = (Math.random() * 10);
}
Use this 用这个
for(int j = 0; j < table[1].length; j++)
System.out.print(table[1][j]+" - ");
Use this 用这个
// table[0] == 1st row
// table[1] == 2nd row
// etc..
for(int i = 0; i < table[1].length; i++)
System.out.println(table[1][i]); // Print each item of the 2nd row
Depending on the usage, you may want to use a method to print a specific row. 根据用法,您可能需要使用一种方法来打印特定的行。 Something like this 像这样
public void printRow(int r){
for(int i=0; i<table[r-1].length; i++){
if(i>0){
System.out.print(", ");
}
System.out.print(table[r-1][i]);
}
}
In this example, you would call printRow(2);
在此示例中,您将调用printRow(2);
when you want to print the 2nd row. 当您要打印第二行时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.