java - 如何通过Java中的给定位置打印矩阵的垂直和水平线?
问题描述
例如我们有一个矩阵:
a b j d e f g k
l m a o p y e s
o k v h e l l o
t h a n k s a m
我有一个给定位置:字符 v 的 row[2] col[2]。我想根据该位置或我得到的任何其他位置打印水平线和垂直线。
我在那个特定位置的水平线应该是:
o k q h e l l o
还有我的垂直线:
j a v a
解决方案
这里“最棘手”的事情实际上只是考虑了您想要的格式。
当我们遍历数组时,对于某些列,我们只需要确保i
或j
等于我们的行或列。例如 - 因为i
对应于我们二维数组中元素的第一个元素:
{“a”、“b”、“j”、“d”、“e”、“f”、“g”、“k”}
那么我们知道i
所有这些元素都必须等于 0。因此我们可以得出结论,要打印一些行,我们只需要确保i
eqaul 与我们想要的行号。我们可以应用类似的逻辑来抓取我们的列。
public class Test {
private String[][] data = {{"a", "b", "j", "d", "e", "f", "g", "k"}, // i == 0
{"l", "m", "a", "o", "p", "y", "e", "s"}, // i == 1
{"o", "k", "v", "h", "e", "l", "l", "o"}, // i == 2
{"t", "h", "a", "n", "k", "s", "a", "m"}}; // i == 3
// j == 0 1 2 3 4 5 6 7
public static void main(String[] args) {
new Test();
}
/**
* Test each of our methods.
*/
public Test() {
// GET THE 3RD (POSITION 2) ROW
System.out.println(getRow(data, 2));
// GET THE 6TH (POSITION 5) COLUMN
System.out.println(getCol(data, 5));
}
/**
* Get some row of some 2D array. This method does not check that
* the row is within the bounds of the 2D array.
*
* @param data
* @param row
* @return
*/
private String getRow(String[][] data, int row) {
String s = "";
int numRows = data.length;
int numCols = data[0].length;
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
if (i == row) {
s += data[i][j];
if (i < (numRows - 1)) s += " ";
}
}
}
return s;
}
/**
* Get some column of some 2D array. This method does not check that
* the column is within the bounds of the 2D array.
*
* @param data
* @param col
* @return
*/
private String getCol(String[][] data, int col) {
String s = "";
int numRows = data.length;
int numCols = data[0].length;
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
if (j == col) {
s += data[i][j];
if (j < (numCols - 1)) s += " ";
}
}
}
return s;
}
}
推荐阅读
- javascript - 使用 foreach 将模板作为参数传递给自定义组件
- java - 在 Spring 中获取自定义存储库的域类型
- r - 如何在 ggplot R 中为 MAC OS Mojave 上的法语字符绘制绘图
- php - 合并 DataTable 中的两列
- multithreading - 如何提高大型 for 循环的速度
- python - 用于 Python 中用户输入的自动斜线
- php - PHP 脚本的结果未显示在 Wordpress 页面上
- sql-server - SQL Server 对“SELECT WHERE IN”查询使用扩展字符范围
- python - 如何将数据从 Gtk 对话框传递/返回到主应用程序类
- c - 如何用C语言从COM口读取数据