簡體   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