java - 将用户输入的数字推入二维数组以形成 4 列和 3 行
问题描述
我正在处理一个两部分的任务,其中第一部分是创建一个 3 行和 4 列的数组,然后让用户输入 4 个数字来组成第一行的第一列。所以如果用户输入 1,2,3,4 那么数组应该打印出来:(0 只是任务的第二部分的空白。
1 2 3 4
0 0 0 0
0 0 0 0
到目前为止,这就是我所拥有的,但我只使用 Java 几天,我确信我没有清楚地看到我的错误。对于我做错的事情,我真的很感激。
这是我的代码:
import java.util.Scanner;
public class multipleElements {
public static void main(String[] args) {
//set up the array and assign variable name and table size
int[][] startNum = new int[3][4];
//set user input variable for the array
Scanner userInput = new Scanner(System.in);
for (int i = 0; i < startNum.length; i++) {
//get user input
System.out.print("please enter your value: ");
//push into the array
String inputValue = userInput.nextInt();
startNum[i][0] = inputValue;
startNum[i][0] = userInput
}
}
}
至于任务的第二部分,第二行和第三行需要是该列第一行输入的任何数字的倍数。所以它看起来像这样:
1 2 3 4
2 4 6 8
3 6 9 12
我还不确定我将如何做到这一点,所以任何关于我可以从哪里开始研究或我应该研究什么的建议也将不胜感激。
解决方案
请尝试以下代码:
public static void main(String[] args) {
//set up the array and assign variable name and table size
int[][] startNum = new int[3][4];
//set user input variable for the array
Scanner userInput = new Scanner(System.in);
for (int i = 0; i < startNum[0].length; i++) {
System.out.print("please enter your value: ");
int inputValue = userInput.nextInt();
startNum[0][i] = inputValue;
}
for (int i = 1; i < startNum.length; i++) {
for (int j = 0; j < startNum[0].length; j++) {
startNum[i][j] = (i + 1) * startNum[0][j];
}
}
}
在第一个循环中,您从用户那里获取值并设置二维数组的第一行。
在第二个 for 循环(2 fors)中,您正在为第一行的每一列设置第二个和第三个循环的值。这就是为什么第一个 for 循环从 i=1 开始,第二个 for 循环从 j=1 开始。
推荐阅读
- javascript - alexa“未定义”对“repromptSpeech”没有响应
- web3js - 从输入数据中查找函数名和参数
- regex - 如何在字符之间查找和替换
- unity3d - 如何统一控制另一个场景中的音频开/关
- javascript - 如何使用复选框检查是否选择了相同性别?
- ios - 获取文档目录iOS Swift中每个项目的属性
- ios - Xamarin Forms:移植到 WkWebView 后发生零星崩溃
- php - PHP `json_encode` 错误地将数组转换为 `{}`
- google-sheets - 如何在单个电子表格单元格中获取逗号分隔变量的值和变量计数的总和?
- typescript - Vue CLI 的类型检查服务忽略了内存限制