Home > OS >  How do I enter data from user input into a 2D array in Java?
How do I enter data from user input into a 2D array in Java?

Time:04-10

I have a 2D array that needs it's values to be changed based on user input.

private static double nursesArray[][] = {
        {2020, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        {2021, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        {2022, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        {2023, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        {2024, 0, 0, 0, 0, 0, 0, 0, 0, 0}
};

The program revolves around it asking the user for the base wage in the year 2020 for the second column (index 1). The program will then ask the user to enter the percent differences in each of the years below, going down each row in that same column. This process needs to be iterated in each of the columns all the way to the end.

The way I have the rest of my code set up is that it uses the array as an argument for the method.

public class nursesUnion {

    private static double nursesArray[][] = {
            {2020, 0, 0, 0, 0, 0, 0, 0, 0, 0},
            {2021, 0, 0, 0, 0, 0, 0, 0, 0, 0},
            {2022, 0, 0, 0, 0, 0, 0, 0, 0, 0},
            {2023, 0, 0, 0, 0, 0, 0, 0, 0, 0},
            {2024, 0, 0, 0, 0, 0, 0, 0, 0, 0}
    };

    public static void dataEntry(double arr[][]) {
        Scanner inp = new Scanner(System.in);
    }
...

I really have no idea where to begin for this. Java is a new language for me and I haven't fully wrapped my head around it yet.

CodePudding user response:

Assuming user already knows how many values they need to enter, you can start with this basic verion:

    public static void dataEntry(double arr[][]) {
        Scanner inp = new Scanner(System.in);

        int rows = nursesArray.length;
        int columns = nursesArray[0].length;

        for (int row = 0; row < rows; row  ) {
            System.out.println("Please, enter values for year "   nursesArray[row][0]);

            // starts with 1 to skip the year.
            for (int column = 1; column < columns; column  ) {
                nursesArray[row][column] = inp.nextDouble();
            }
        }
    }

It just iterates trough rows and columns from left to right, from to to bottom.

CodePudding user response:

public static void dataEntry(double arr[][]) {
    Scanner inp = new Scanner(System.in);
    for(int column = 1; column < arr[0].length; column  ){
        System.out.println("Enter base wage for col:" column);
        arr[0][column]=inp.nextInt();     
        System.out.println("Enter % increase per year");
        int increase=inp.nextInt();
        for(int row=1; row<arr.length; row  ){
            arr[row][col]  = arr[row-1][column]*increase/100;
        }
    }
}
  • Related