java - 我将如何着手将此代码转换为手动将参数提供给该方法并返回一个 2D char 数组?
问题描述
public static void tehtava7() {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Give height");
int height = input.nextInt();
char[][] array = new char[height][height];
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[row].length; col++) {
if (row == col || col == 0 || col == height - 1) {
array[row][col] = 'X';
} else {
array[row][col] = ' ';
}
}
}
printTwoDimCharArray(array);
}
public static void printTwoDimCharArray(char[][] myarray) {
for (int i = 0; i < myarray.length; i++) {
for (int j = 0; j < myarray[i].length; j++) {
System.out.print(myarray[i][j]);
}
System.out.println();
}
}
public static void main(String[] args) {
tehtava7();
}
我需要手动将参数提供给该方法,并根据height * height
我提供给该方法的值返回一个 2D 字符数组。它还应该N
根据给定的参数打印相同的形状。我该怎么做呢?所以基本上我不会问用户高度,而是手动导入。
解决方案
我不会问用户,
height
而是手动导入。
首先,我建议您将height
其视为函数的参数。
前:
public static void tehtava7() {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Give height");
int height = input.nextInt();
char [][] array = new char[height][height];
// ...
后:
public static void tehtava7(int height) {
// ^--- NOTICE: NEW PARAMETER
char [][] array = new char[height][height];
// ...
接下来,确定您希望如何“导入”它。
使用高度数组导入:
前:
public static void main(String[] args) {
tehtava7();
}
后:
public static void main(String[] args) {
int[] heights = new int[] { 2, 4, 6, 8, 10 }; // heights to import
for(int height : heights) {
tehtava7(height);
// ^---- NOTICE: LOOP AGAINST PARAMETERS
}
}
...或直接从命令行导入参数:
public static void main(String[] args) {
// args = command line options
// loop over command line options, convert to integer
int[] heights = new int[args.length];
for(int i = 0; i < args.length; ++i) {
heights[i] = Integer.parseInt(args[i]);
}
for(int height : heights) {
tehtava7(height);
// ^---- NOTICE: LOOP AGAINST PARAMETERS
}
}
java MyClass 2 4 6 8
输出:
XX
XX
X X
XX X
X XX
X X
X X
XX X
X X X
X X X
X XX
X X
X X
XX X
X X X
X X X
X X X
X X X
X XX
X X
推荐阅读
- flutter - 如何让 url 启动器发送电子邮件?
- android - android-recycleView item on drop 没有使用 sqlite 正确排序
- consistency - etcd:强、线性和顺序一致性
- visual-studio-code - 如何关闭 VS Code 中的工具提示/建议?
- c# - 在linq c#中使用参数搜索查询
- gsub - 如何使用 gsub() 重命名 df 中的变量?
- javascript - 如何通过动态键对数组进行分组?
- node.js - 调用 Lambda 以向连接的 websocket 发送消息
- java - 如何使用 Smack 4 创建空 IQ 数据包
- python - Python3 Matplotlib psutil 脚本未运行