繁体   English   中英

将用户输入的数字推入二维数组以形成 4 列 3 行

[英]Pushing user input numbers into a 2D Array to form 4 columns with 3 rows

我正在处理一个由两部分组成的任务,其中第一部分是创建一个 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 开始。

for (int i = 0; i < startNum[0].length; i++) {
    // get user input
    System.out.print("please enter your value: ");

    // push into the array
    int inputValue = userInput.nextInt(); // <-- assign to an int value
    // assigns the user input to the columns of 0th row
    startNum[0][i] = inputValue; 

    //startNum[i][0] = userInput // <-- not required
}

for (int i = 1; i < startNum.length; i++) {
    for (int j = 0; j < startNum[0].length; j++) {
        // starting from 1st row calculate the values for all the rows
        // for a column and then move on to next column once finished
        startNum[i][j] = startNum[0][j] * (i + 1); 
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM